我试图在派生类中使用增量运算符。但我无法做到这一点。
#include<iostream>
using namespace std;
class Base {
private:
int a;
public:
int x, y, z;
int Converter(int data) {
cout << "Printing z: " << z << endl;
return data * x + y;
}
Base& operator=(int rhs) {
a = Converter(rhs);
return *this;
}
Base(int a, int x, int y, int z) : a(a), x(x), y(y), z(z) {}
explicit Base(int a_) : a(a_) {}
Base operator+(const Base& obj){
Base x(*this);
return Base(x.a + obj.a);
}
Base& operator++() { return *this = *this + Base(Converter(1)); }
};
class Derived : Base {
public:
Derived() : Base(0, 1, 2, 3) {} // Come constants for x, y, z
explicit Derived(int data) : Base(data, 1, 2, 3){}
using Base::operator=;
using Base::operator++;
};
int main(){
Derived x(10);
++x;
x = 1;
}
我认为问题在于上面注释的突出显示行。当我试图打印运算符++()函数中的值x,y,z时,它显示为0,尽管我在派生类定义中将它们初始化为1,2,3。
我尝试调用另一个构造函数,如下所示,但仍然没有用。
Base& operator++() { return *this = *this + Base(Converter(1), this->x, this->y, this->z) }
所产生的产出是:
Printing z: 3
Printing z: 0
如果我像下面一样颠倒main()中的顺序,则输出是不同的。
x = 1;
++x;
输出:
Printing z: 3
Printing z: 3
有人能给我指个正确的方向吗?
谢了。
这个代码的含义是不可能理解的。我不知道你想干什么。
但是
explicit Base(int a_) : a(a_) {}
(这实际上使
正在此处调用该构造函数
return Base(x.a + obj.a);
并且从此处重载的
Base& operator++() { return *this = *this + Base(Converter(1)); }
该序列用z等于0的对象覆盖的值,并在下一行代码
正如我所说的,我不知道这段代码要做什么,所以我也不知道作为修复建议什么,但是希望这解释了这个值的来源。