c++ - 如何从派生类访问基类中的重载运算符?

标签 c++ class inheritance operator-overloading operators

请参阅以下代码:

#include<iostream>

using namespace std;


class ex
{
    int i;
public:
    ex(int x){i=x;}
    void operator-()
    {
        i=-i;
    }
    int geti(){return i;}
};

class derived:public ex
{
    int j;
public:
    derived(int x,int y):ex(x){j=y;}
    void operator-()
    {
     j=-j;
    }
    int getj(){return j;}
};


int main()
{
    derived ob(1,2);
    -ob;
    cout<<ob.geti();
    cout<<"\n"<<ob.getj();
}

输出:

1
-2
Process returned 0 (0x0)   execution time : 0.901 s
Press any key to continue.

我在基类和派生类中都定义了 - 运算符,但 -ob; 仅调用派生类的运算符。那么如何将 i 字段也更改为 -i (调用基类中的运算符)。

我需要任何显式函数来实现此目的吗?

最佳答案

看来你的意思是

void operator-()
{
    ex::operator -();
    j=-j;
}

无论如何,最好声明运算符,例如

ex & operator-()
{
    i = -i;

    return *this;
}

derived & operator-()
{
    ex::operator -();

    j = -j;

    return *this;
}

您还可以将运算符(operator)设置为虚拟。例如

#include<iostream>

using namespace std;


class ex
{
    int i;
public:
    virtual ~ex() = default;

    ex(int x){i=x;}
    virtual ex & operator-()
    {
        i = -i;

        return *this;
    }

    int geti(){return i;}
};

class derived:public ex
{
    int j;
public:
    derived(int x,int y):ex(x){j=y;}
    derived & operator-() override
    {
        ex::operator -();

        j = -j;

        return *this;
    }
    int getj(){return j;}
};


int main()
{
    derived ob(1,2);

    ex &r = ob;

    -r;

    cout<<ob.geti();
    cout<<"\n"<<ob.getj();
}    

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

相关文章:

c# - C# 中的 C++ 模板继承等效于什么?

c++ - 在函数调用期间暂时禁用窗口

c++ - 在模板函数中使用 auto 和 decltype

c++ - 将 C++ 链接到静态库; undefined reference 错误

c++ - 单独定义模板化嵌套类方法的正确语法

c++ - 运算符不使用类对象?

jsf - 从 RuntimeException 继承的类的错误页面问题

c++ - 一个类的初学者C++程序

c# - 非典型系统中的命名空间和类命名最佳实践

c++ - 在 Arduino 中使用虚拟方法