【发布时间】:2016-08-24 14:50:38
【问题描述】:
我见过很多人将他们的函数参数设置为:
function(const myType &myObj)
我不明白他们为什么在类型后面使用&?
看来const 足以阻止构造函数被调用。
因此,我编写了以下代码,但我认为结果没有任何优势。谁能解释一下?
#include <iostream>
using namespace std;
class myclass
{
public:
myclass()
{
cout<<"constructor is called\n";
}
int field;
};
void func1(myclass a)
{
cout<<"func1: "<<a.field<<"\n";
}
void func2(const myclass a)
{
cout<<"func2: "<<a.field<<"\n";
}
void func3(const myclass &a)
{
cout<<"func3: "<<a.field<<"\n";
}
int main ()
{
myclass obj;
obj.field=3;
cout<<"----------------\n";
func1(obj);
cout<<"----------------\n";
func2(obj);
cout<<"----------------\n";
func3(obj);
cout<<"----------------\n";
return 0;
}
结果:
constructor is called
----------------
func1: 3
----------------
func2: 3
----------------
func3: 3
----------------
【问题讨论】:
-
这不是关于默认构造函数,而是关于copy constructor,在你的情况下是generated automatically。请看The Definitive C++ Book Guide and List
-
const与是否调用构造函数无关
标签: c++ c++11 constructor constants