为什么分配操作员不能按预期工作



UPD:我现在明白这个问题有多愚蠢了,这只是我对C++构造的误解。

我遇到了操作员分配问题——它没有按预期工作。下面是示例代码:

#include <iostream>
class TestClass{
private:
int pop;
public:
TestClass(){
std::cout<<"Default Constuctorn";
}
TestClass(int i):pop(i){
std::cout<<"Param Constuctorn";
}
TestClass &operator=(const TestClass &other){
std::cout<<"Assignment Operator n";
return *this;
}
friend std::ostream &operator<<(std::ostream &out, TestClass &x);
};
std::ostream &operator<<(std::ostream &out, TestClass &x){
out<<" This is the TestClass with pop=" << x.pop <<"n";
return out;
}

int main()
{
TestClass    P0(333);
TestClass P_foo(555);
P_foo = P0;
std::cout << P0;
std::cout << P_foo;
return 0;
}

这个程序的结果是

Param Constuctor
Param Constuctor
Assignment Operator 
This is the TestClass with pop=333
This is the TestClass with pop=555

因此CCD_ 1对象保留初始化值555。如果我注释掉我的自定义赋值运算符,程序将按预期工作。

Param Constuctor
Param Constuctor
This is the TestClass with pop=333
This is the TestClass with pop=333

我的赋值运算符函数出了什么问题?

我的赋值运算符函数出了什么问题?

operator=:的实现中,*this在任何时候都不会被修改

TestClass &operator=(const TestClass &other){
std::cout<<"Assignment Operator n";
return *this;
}

我看到这个代码有几个问题:

  • pop没有在默认构造函数中初始化(您没有调用它,但如果您要手动实现它,您仍然应该正确地实现它(。

  • operator=根本没有更新this->pop的值,这是问题的根本原因。如果您声明operator=,则您有责任自己正确地实现它,编译器将对您毫无帮助。但是,如果您没有声明operator=,编译器将自动生成一个默认实现,该实现将为您分配pop值的副本。

  • P_foo0应通过const引用获取TestClass参数。

试试这个:

#include <iostream>
class TestClass{
private:
int pop;
public:
TestClass() : pop(0) { // <-- add this value!
std::cout << "Default Constructorn";
}
TestClass(int i) : pop(i) {
std::cout << "Param Constructorn";
}
TestClass& operator=(const TestClass &other){
std::cout << "Assignment Operatorn";
pop = other.pop; // <-- add this!
return *this;
}
friend std::ostream& operator<<(std::ostream &out, const TestClass &x);
};
std::ostream& operator<<(std::ostream &out, const TestClass &x){
out << " This is the TestClass with pop=" << x.pop << "n";
return out;
}
int main()
{
TestClass    P0(333);
TestClass P_foo(555);
P_foo = P0; // <-- this will work as expected now
std::cout << P0;
std::cout << P_foo;
return 0;
}
TestClass &operator=(const TestClass &other){
std::cout << "Assignment Operator n";
pop = other.pop;    // You need to add this
return *this;
}

问题是您定义的赋值运算符没有将任何内容分配给它所调用的实例。

再次阅读您的操作员:

TestClass &operator=(const TestClass &other){
std::cout<<"Assignment Operator n";
return *this;
}

你可以看到发生了两件事。打印Assignment Operator并且返回*this。但是你的";其他";根本不使用TestClass,并且this中的数据从未被修改。

你可以通过分配给this->pop来解决这个问题,就像这样:

TestClass &operator=(const TestClass &other){
std::cout<<"Assignment Operator n";
pop = other.pop; // Now this->pop will be assigned a new value from other.pop
return *this;
}

现在,当您分配P_foo = P0时,P_foo将成功地分配来自P0的pop值。

最新更新