c++ - 在 C++ 中使用赋值运算符重载将类对象的数据复制到另一个类对象时出错

标签 c++ operator-overloading assignment-operator

我试图将一个类对象的值复制到另一个类对象,但赋值运算符重载方法不起作用。

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/

相关文章:

C++ 程序显然打印内存地址而不是数组

c++ - 无法在动态链接库中找到过程入口点 _ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEC1Ev

c++ - C++如何调用成员函数的指针

c++ - 编译器抛出 "ambiguous overload for operator"

c++ - 如何在没有 operator=() 的情况下为 const 成员 push_back?

c++ - 指向数组元素的指针打印内存地址而不是元素的值

c++ - 运算符++ 中的 Int 参数

c++ - 这是 operator<</>> 的正确实现吗?

c++ - 通过 'new'实现赋值的一种方法

haskell - 让 5 = 10 做什么?这不是赋值操作吗?