我试图将一个类对象的值复制到另一个类对象,但赋值运算符重载方法不起作用。
class rectangle
{
int length,breadth;
public:
rectangle(int l,int b)
{
length=l;
breadth=b;
}
rectangle operator =(square s) //This line is giving me error.
{
breadth=length=s.seee();
cout<<"length"<<length;
}
int see() const
{
return length;
}
};
class square
{
int side;
public:
square()
{
side=5;
}
square operator =(rectangle r)
{
side=r.see();
cout<<side;
}
int seee() const
{
return side;
}
};
错误= 's' 的类型不完整。 我该如何解决这个错误?请帮忙!
最佳答案
您需要在定义square
之后执行成员函数。另请注意,赋值运算符应返回对被赋值对象的引用 this
,并且操作的右侧(在本例中为 square
) 通常被视为 const&
以避免不必要的复制。
class rectangle
{
//...
rectangle& operator=(const square&);
//...
};
class square
{
//...
};
rectangle& rectangle::operator=(const square& s)
{
breadth=length=s.seee();
return *this;
}
关于c++ - 在 C++ 中使用赋值运算符重载将类对象的数据复制到另一个类对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58248187/