使用重载赋值运算符

时间:2014-08-04 18:22:53

标签: c++ templates operator-overloading copy-constructor

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

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

class BA作为成员,它拥有重载的赋值运算符和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 个答案:

答案 0 :(得分:3)

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

关于comment

  

A有点复杂并且包含链接列表。每次复制A的对象时,都必须更新链表

每次复制对象时都必须更新一个对象听起来有点可疑。旧的std::auto_ptr类几乎就是这样,它通过涉及特殊代理引用类的hack实现了效果。 可能您的对象不是真正可复制但只是可移动的,在这种情况下,不要使用复制分配运算符进行任何操作是,但使用例如一个普通的命名成员函数。