请参阅以下代码:
#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/