为什么拷贝构造函数的参数需要加const和引用?
引用:
(值传递)实参到形参的传递过程,形参需要创建新的对象并接收实参的拷贝过程,因此会调用拷贝构造函数。
若拷贝构造函数采用值传递,将会循环调用本身,被编译器所禁止。
const:
为保证程序安全,加上const防止对引用类型参数值的意外修改。
#include <iostream> using namespace std; class CExample { public: CExample(int x) : m_nTest(x) { cout << "constructor with argument." << endl; } CExample(const CExample& ex) { m_nTest = ex.m_nTest; cout << "copy constructor." << endl; } CExample& operator = (const CExample &ex) { cout << "assignment operator." << endl; m_nTest = ex.m_nTest; return *this; } void myTestFunc(CExample ex){ } private: int m_nTest; }; int main() { CExample aaa(2); CExample bbb(3); bbb = aaa; CExample ccc = aaa; bbb.myTestFunc(aaa); system("pause"); return 0; }
constructor with argument.
constructor with argument.
assignment operator.
copy constructor.
copy constructor.
请按任意键继续. . .