class person { public: virtual void a() = 0; }; class common : public person { public: void a() { cout << "Common person buys a ticket." << endl; } }; class student : public person { public: void a() { cout << "Student buys a discounted ticket." << endl; } }; class military : public person { public: void a() { cout << "Military personnel buys a free ticket." << endl; } }; void b(person* p) { p->a(); } int main() { person* p1 = common(); person* p2 = student(); person* p3 = military(); b(p1); b(p2); b(p3); return 0; }将此代码用静态联编实现
时间: 2024-01-15 16:03:27 浏览: 72
静态联编也称为早期绑定,是指在编译期间确定函数的调用对象,通常使用函数重载实现。在此代码中,我们可以使用函数重载实现静态联编。
```c++
#include <iostream>
using namespace std;
class person {
public:
virtual void a() = 0;
};
class common : public person {
public:
void a() {
cout << "Common person buys a ticket." << endl;
}
};
class student : public person {
public:
void a() {
cout << "Student buys a discounted ticket." << endl;
}
};
class military : public person {
public:
void a() {
cout << "Military personnel buys a free ticket." << endl;
}
};
void b(common* c) {
c->a();
}
void b(student* s) {
s->a();
}
void b(military* m) {
m->a();
}
int main() {
common* c = new common();
student* s = new student();
military* m = new military();
b(c);
b(s);
b(m);
delete c;
delete s;
delete m;
return 0;
}
```
在静态联编中,我们使用了函数重载,将函数b分别定义为操作common、student和military对象的函数。在main函数中,我们创建了一个common指针指向common对象,一个student指针指向student对象,一个military指针指向military对象,然后分别调用它们的b函数,输出结果与之前使用动态联编的结果相同。
静态联编的缺点是不支持多态,无法在运行时确定函数的调用对象,因此需要在编译期间确定函数的类型。如果需要支持多态,需要使用动态联编。
阅读全文