C++ 重载增量运算符++;在派生类中继承
我试图在派生类中使用增量运算符。但我无法做到这一点C++ 重载增量运算符++;在派生类中继承,c++,C++,我试图在派生类中使用增量运算符。但我无法做到这一点 #include<iostream> using namespace std; class Base { private: int a; public: int x, y, z; int Converter(int data) { cout << "Printing z: " << z <<
#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;
}
产出为:
Printing z: 3
Printing z: 0
如果我像下面那样颠倒main()中的顺序,则输出是不同的
x = 1;
++x;
输出:
Printing z: 3
Printing z: 3
有人能给我指出正确的方向吗
谢谢。代码的含义无法理解。我不知道你想做什么 但是,
打印z:0
输出的原因很清楚。它来自这个构造函数
explicit Base(int a_) : a(a_) {}
(这实际上使z
未初始化,但我猜您的系统上得到了0)
这里正在调用该构造函数
return Base(x.a + obj.a);
返回语句是从重载的操作符+
调用的
Base& operator++() { return *this = *this + Base(Converter(1)); }
该序列用z等于0的对象覆盖*此
的值,该值在下一行代码x=1上输出代码>
正如我所说,我不知道这段代码试图做什么,所以我不知道作为修复建议应该做什么,但希望这能解释这个值的来源。这段代码不应该编译。您承诺在operator+()
中返回Base
,但不返回任何内容。@scohe001更正错误后,我已重新加载。现在它可以编译了。这个程序显示出未定义的行为,通过到达非void
函数Base::operator+
的右大括号,而不会遇到return
语句。@RD1153没有警告它不会编译。有几个错误,它们是非常基本的东西。编译器应该在这里帮助您。阅读错误和警告。
Base& operator++() { return *this = *this + Base(Converter(1)); }