使用重载赋值操作符

Using overloaded assignment operator

本文关键字:赋值操作符 重载      更新时间:2023-10-16

我有一个具有非默认构造函数和重载赋值操作符的template<> class A:

template<typename T>
class A
{
  public:
  A(T x);
  A(A<T> &parent);
  A<T> & operator=(A<T> &rhs);
};

class B,其中A是成员,它有自己的重载赋值操作符和a

的getter方法。
class B
{
  public:
  B();
  B& operator=(B &rhs);
  A<int> get_A();
  protected:
  A<int> *member;
};

我已经定义了赋值操作符和A getter方法如下:

B& B::operator=(B &rhs)
{
  *member = rhs.get_A();
  return *this;
}
A<int> B::get_A()
{
  return *member;
}

赋值操作符在这种情况下不起作用。我遗漏了什么吗?我得到以下错误:

B.cpp(92): error: no operator "=" matches these operands
            operand types are: A<int> = A<int>

我也试过

B& B::operator=(B &rhs)
{
  A<int> temp(rhs.get_A());
  *member = temp;
  return *this;
}
在这种情况下,我得到:
B.cpp(92): error: no instance of constructor "A<T>::A [with T=int]" matches the argument list
            argument types are: (A<int>)
    A<int> temp(rhs.get_A());

1

关于

A<T> & operator=(A<T> &rhs);

最好是

A<T>& operator=(A<T> const& rhs);


2

关于

B& B::operator=(B &rhs)
{
  *member = B.get_A();
  return *this;
}

最好是

B& B::operator=(B const& rhs)
{
  *member = rhs.get_A();
  return *this;
}


3

关于

  B() : member(4);
不能编译的

很难说它应该是什么,因为member被声明为指针,而提供的值是一个不兼容的整数。


4

关于

A<int> get_A();

最好是

A<int> get_A() const;

可以在const对象上调用。


5

关于

注释

A稍微复杂一些,包含一个链表。每次复制A的对象时,都必须更新链表

对象每次复制时都必须更新,这听起来确实有点可疑。旧的std::auto_ptr类几乎就是这样,它通过一个涉及特殊代理引用类的黑客来实现这种效果。可能你的对象不是真正可复制的,而只是可移动的,在这种情况下,无论操作是什么,都不要使用复制赋值操作符,而是使用普通的命名成员函数。