Cpp / 拷贝构造函数的参数为什么必须使用引用类型
生活随笔
收集整理的這篇文章主要介紹了
Cpp / 拷贝构造函数的参数为什么必须使用引用类型
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
表面原因:編譯器無法通過,會報如下錯誤:
error: invalid constructor; you probably meant ‘CExample (const CExample&)’CExample(CExample ex) //拷貝構造函數深層次原因是避免拷貝構造函數無限制的遞歸下去。?
栗子:
#include <iostream>class CExample {int m_nTest;public:CExample(int x) : m_nTest(x){std::cout << "constructor with argument\n";}CExample(const CExample &ex){m_nTest = ex.m_nTest;std::cout << "copy constructor\n";}CExample &operator=(const CExample &ex){std::cout << "assignment operator\n";m_nTest = ex.m_nTest;return *this;}void myTestFunc(CExample ex){} };int main() {CExample aaa(2); // 輸出:constructor with argumentCExample bbb(3); // 輸出:constructor with argumentbbb = aaa; // 輸出:assignment operatorCExample ccc = aaa; // 輸出:copy constructorbbb.myTestFunc(aaa); // 輸出:copy constructorreturn 0; }假設拷貝構造函數是傳值的,那么在執行如下代碼:
CExample ccc = aaa;會將 aaa 傳值到形參,此時構造形參實例時會調用拷貝構造函數,這就造成了無限地構造下去,直至堆棧耗盡,所以為了避免這個問題的發生,直接從編譯器的角度禁用了該問題。
?
參考:拷貝構造函數的參數為什么必須使用引用類型_『小豬呼嚕嚕』的專欄 -- I Write,therefore I am.-CSDN博客_拷貝構造函數的參數
(SAW:Game Over!)?
?
?
總結
以上是生活随笔為你收集整理的Cpp / 拷贝构造函数的参数为什么必须使用引用类型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++中,有哪4种与类型转换相关的关键字
- 下一篇: Cpp / std::string 实现