c++ - 对于派生类对象的基类部分,如何在基类中实现运算符重载?

标签 c++

对于派生类对象的基类部分,如何在基类中实现运算符重载?

请查看此示例代码并实现基类部分以在派生类对象上实现 * 运算符

class base {
     int x;
public:

};

class der : public base {
    int y;
public:
    const der operator*(const der& rh) {
        der d;
        d.y = y * rh.y;
        return d;
    }

};

最佳答案

class base {
     int x;
public:
     base & operator *=(const base &rh) {
         x*=rh.x;
         return *this;
     }
     base operator *(const base &rh) {
         base b = *this;
         b*=rh;
         return b;
     }
};

class der : public base {
    int y;
public:
    using base::operator*;
    der & operator*= (const der& rh) {
         base::operator*=(rh);
         y*=rh.y;
         return *this;
    }
    const der operator*(const der& rh) {
        der d = *this;
        d*=rh;
        return d;
    }

};

关于c++ - 对于派生类对象的基类部分,如何在基类中实现运算符重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10225716/

相关文章:

c++ - 压缩库 Windows 运行时

c++ - 需要澄清文字类型的定义

c++ - 成员变量包装器

c++ - 在 C++ 中匹配俄语元音

C++ Qt - 以编程方式检查 Steam 游戏是否正在运行

c++ - 未处理的 C++ 异常中的 DUMP

c++ - 当存在可用的右值构造函数时,为什么会从右值调用类引用构造函数重载?

c++ - 从 C++ 线程调用 python 脚本,GIL

c++ - MFC如何解释SetWindowTextW(LPCTSTR)?

c++ - 模板参数序列的模板函数调用序列