如何在c++中覆盖此虚拟运算符

How to override this virtual operator in c++?

本文关键字:虚拟 运算符 覆盖 c++      更新时间:2023-10-16

基本结构在头文件中定义如下:

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