如何在c++中覆盖此虚拟运算符
How to override this virtual operator in c++?
基本结构在头文件中定义如下:
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
相关文章:
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- C++:从抽象类重写纯虚拟运算符重载
- 虚拟超载运算符>>和<<
- 冲突的 CLANG"虚拟 dtor"和"已弃用的复制运算符"警告
- 如何将运算符重载为虚拟运算符
- 使用范围解析运算符时,在构造函数中调用虚拟方法是否安全?
- 基类和派生类的虚拟插入运算符重载
- 重载纯虚拟运算符
- 具有虚拟赋值运算符的多态性
- C++ 中的纯虚拟赋值运算符
- 超级多重非虚拟继承中基类的作用域运算符
- 是否可以完全模拟虚拟运算符++(int)?
- C++抽象基类,具有纯虚拟运算符+函数
- 虚拟运算符重载
- 如何在c++中覆盖此虚拟运算符
- C++-虚拟运算符=在派生实例的基类上调用
- 为什么在基类而不是派生类上调用虚拟运算符==
- 在派生类中重新定义虚拟运算符==
- C++ 重载虚拟 + 运算符
- 重载虚拟运算符 -> ()