sri*_*anp 2 c++ inheritance class 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();
}
Run Code Online (Sandbox Code Playgroud)
输出:
1
-2
Process returned 0 (0x0) execution time : 0.901 s
Press any key to continue.
Run Code Online (Sandbox Code Playgroud)
我-在基类和派生类中都定义了运算符,但-ob;只调用派生类的运算符。那么如何将i字段更改为-i(调用基类中的运算符)。
我需要任何显式函数来实现这一点吗?
看来你的意思
void operator-()
{
ex::operator -();
j=-j;
}
Run Code Online (Sandbox Code Playgroud)
在任何情况下,最好声明运营商,例如
ex & operator-()
{
i = -i;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
和
derived & operator-()
{
ex::operator -();
j = -j;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
您还可以使操作员虚拟。例如
#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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
143 次 |
| 最近记录: |