簡體   English   中英

使用重載的賦值運算符

[英]Using overloaded assignment operator

我有一個帶有非默認構造函數和重載賦值運算符的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對象時,都必須更新鏈表

聽起來確實有些麻煩,因為每次復制對象時都必須對其進行更新。 舊的std::auto_ptr類幾乎就是這樣,並且它通過涉及特殊代理引用類的hack達到了效果。 可能是你的對象不是真正的復制,但是僅僅移動,在這種情況下,不使用拷貝賦值運算符的任何操作確實是,但使用例如一個普通的命名成員函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM