基础结构在头文件中是这样定义的:
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
};
我对前两个虚运算符声明感到困惑,假设我有一个新类继承了基类,我该如何重写这两个运算符,以便当子类对象被视为基类时,这两个函数可以叫什么?
最佳答案
就像您覆盖的任何其他函数一样。
#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
关于c++ - 如何在 C++ 中覆盖这个虚拟运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36963684/