基本结构在头文件中定义如下:
struct Base {
virtual operator char * (void) {
return 0;
}
virtual operator long (void) { // hash function
return 0;
}
virtual long operator == (Base & base) {// isequal function
return *this == base;
}
Base (void) {} // new_element
virtual ~Base (void) {} // delete_element
virtual ostream & Write (ostream & stream) = 0;// write_element
};
我对前两个虚拟运算符声明感到困惑,假设我有一个新类继承了基类,我如何重写这两个运算符,以便当子类对象被视为Base类时,这两个函数可以是叫?
答案 0 :(得分:4)
就像你覆盖的任何其他功能一样。
#include <iostream>
#include <vector>
using namespace std;
struct A
{
virtual operator char * (void)
{
return 0;
}
};
struct B : A
{
operator char * (void) override
{
return (char*)12;
}
};
struct C : A
{
operator char * (void) override
{
return (char*)24;
}
};
int main()
{
vector<A*> v;
v.push_back(new A);
v.push_back(new B);
v.push_back(new C);
for (auto e : v)
{
char* p = *e;
cout << "p=" << (int)p << endl;
}
for (auto e : v)
{
delete e;
}
return 0;
}
这将打印:
p=0
p=12
p=24