簡體   English   中英

定義賦值運算符和復制構造函數

[英]Defining both Assignment operator and copy constructor

假設我有一個類A。我定義了一個復制構造函數和一個賦值運算符重載函數。 當我做

A類; B類= A;

然后在定義B類時,是調用復制構造函數還是賦值運算符?

提前致謝。

編輯:對不起,我提到了錯誤的代碼。 它應該是:

A a; a b = a;

IIRC T t = value調用復制構造函數,可以通過在構造函數中輸出字符串以確定所使用的方法來進行驗證。 IIRC當聲明和賦值在同一行時,它不稱為賦值,而是初始化。

另一方面,您發布的內容沒有任何意義,您不能將一個類型分配給另一種類型,只能分配給類型實例。

編輯:即使您有兩種不同類型的情況(您的問題的上下文對此不清楚):

class A {};

class B {
public:
   B(const A& other)  { cout << "copy"; }
   B& operator=(const A& other) { cout << "assign"; }
};

int main() {
   A a;
   B b = a; // copy con
   B b1(a); // same as above
   b = a;   // assign op
}

即使這樣,當“復制構造函數”和賦值運算符都采用另一種類型時,仍將調用復制構造函數而不是賦值運算符。

假設您實際上的意思是:

A a;
A b = a;

復制構造函數被調用。 標准在此用法中允許=此特殊含義。

使用兩者創建一個簡單的類,並通過在兩者中設置一個斷點來調試要執行的功能。 然后您將看到,並且還將學習一些調試。

讓我們嘗試一下!

#include <iostream>

class A {
 public:
  A() {
    std::cout << "default constructor\n";
  }
  A(const A& other) {
    std::cout << "copy constructor\n";
  }
  A& operator=(const A& rhs) {
    std::cout << "assignment operator\n";
    return *this;
  }
};

int main(int argc, char** argv) {
  std::cout << "first declaration: ";
  A a;
  std::cout << "second declaration: ";
  A b(a);
  std::cout << "third declaration: ";
  A c = a;
  std::cout << "fourth declaration: ";
  A d;
  std::cout << "copying? ";
  d = a;
  return 0;
}

打印:

first declaration: default constructor
second declaration: copy constructor
third declaration: copy constructor
fourth declaration: default constructor
copying? assignment operator

這里的工作示例: http : //codepad.org/DNCpqK2E

當您定義新對象並為其分配另一個對象時。 它調用復制構造函數。 例如,復制構造函數調用:

Class A;
Class B=A;

分配操作員呼叫:

Class A;
Class B;
B=A;

您始終可以通過在兩種方法中編寫“ print”語句來找出正在調用的方法來進行測試。

希望能有所幫助...

暫無
暫無

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

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