关于c++赋值函数返回类对象时的疑义
关于c++赋值函数返回类对象时的疑问
首先我不管返回引用还是对象,这里我想试下返回对象
报了类型不匹配,既然对象引用和对象,有差别,为什么拷贝构造函数,不报类型不匹配
------解决方案--------------------
临时对象不能绑定到非常量左值引用,改成这样。
或这样
------解决方案--------------------
Your answer is close. The correct copy assign function signature is:
The reason OP's has 'no match for oprator=' is because "test3 = test1" will generate a temporary object.
首先我不管返回引用还是对象,这里我想试下返回对象
#include <iostream>
#include <cstring>
using namespace std;
class A
{
public:
A();
A( const char *p );
A( A &a );
A operator = ( A &a ) ;
void show( );
~A();
private:
char *b;
};
A::A()
{
b = NULL;
}
A::A( const char *p )
{
if( p == NULL )
{
b = NULL;
}
else
{
int len = strlen( p ) + 1;
b = new char[len];
strcpy( b,p );
}
}
A::A( A &a )
{
int len = strlen( a.b ) + 1;
b = new char[len];
strcpy( b, a.b );
}
A A::operator =( A &a )
{
if( this == &a )
{
return *this;
}
delete []b;
int len = strlen( a.b ) + 1;
b = new char[len];
strcpy( b, a.b );
return *this;
}
void A::show( )
{
cout<<b<<endl;
}
A::~A()
{
cout<<"delete one object"<<endl;
delete []b;
}
int main()
{
A test1("abc");
A test3(test1);
A test4;
test4=test3=test1;
test4.show();
return 0;
}
报了类型不匹配,既然对象引用和对象,有差别,为什么拷贝构造函数,不报类型不匹配
------解决方案--------------------
临时对象不能绑定到非常量左值引用,改成这样。
A operator = ( A const&a ) ;
或这样
A& operator = ( A &a ) ;
------解决方案--------------------
Your answer is close. The correct copy assign function signature is:
A& A::operator =(const A &a)
The reason OP's has 'no match for oprator=' is because "test3 = test1" will generate a temporary object.