區別 1: 可能只知道 一個效率高一個效率低,具體低在哪裏?
區別 2:成語變量是 引用, 或者const 修飾,必須初始化.
- 區別2 這裏不做解釋, 具體講解1:
如果成員變量類型是 內置類型(int, char ), 那麼初始化和賦值的成本是相同的.這裏的效率高低, 指的是自定的類型(class)
class test
{
public:
test(){
std::cout<<"construct..."<<std::endl;
}
test(test &t)
{
std::cout<<"copy construct ..."<<std::endl;
}
test& operator =(test &t)
{
std::cout<<"copy assignment..."<<std::endl;
return *this;
}
};
class yang
{
public:
yang(test y);
yang(test &y);
test ff;
};
/*賦值 & 參數傳遞方式:賦值*/
yang::yang(test t)
{
ff = t;
}
/*初始化 & 參數傳遞方式:賦值*/
yang::yang(test t):ff(t)
{
}
/*賦值 & 參數傳遞方式:引用*/
yang::yang(test &t)
{
ff = t;
}
/*初始化列表 & 參數傳遞方式:引用*/
yang::yang(test &t):ff(t)
{
}
輸出結果
初始化列表 & 參數傳遞方式:引用
test t;
std::cout<<"----------------"<<std::endl;
yang sen(t);
construct...
----------------
copy construct ... 輸出結果: 只調用了拷貝構造函數
賦值 & 參數傳遞方式:引用
test t;
std::cout<<"----------------"<<std::endl;
yang sen(t);
construct...
----------------
construct...
copy assignment... 輸出結果: 調用了構造函數, 以及拷貝賦值函數
參數傳遞如果不是引用的話, 更離譜
初始化 & 參數傳遞方式:賦值
construct...
test t;
std::cout<<"----------------"<<std::endl;
yang sen(t);
construct...
----------------
copy construct ...
copy construct ... 兩次拷貝構造
賦值 & 參數傳遞方式:賦值
test t;
std::cout<<"----------------"<<std::endl;
yang sen(t);
construct...
----------------
1: copy construct ...
2: construct...
3: copy assignment...
解釋下:
1: copy construct ... 是調用 yang sen(t) 進行參數傳遞,
2: construct... 是定義 test ff;
3: copy assignment... 是對ff賦值 ff = t;
如有哪裏不對的地方, 請指出,後期會更改