1)当类中没有定义任何一个构造函数时,C++编译器会提供默认无参构造函数和默认拷贝构造函数。
2)当类中定义了拷贝构造函数时,C++编译器不会提供无参构造函数。
3)当类中定义了任意的非拷贝构造函数,即类中提供了有参构造函数,C++编译器不会提供无参构造函数。
4)默认拷贝构造函数成员变量只进行简单赋值
总结:只要你写了构造函数,那么你就必须要用!!!
// 构造函数使用规则.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Location{
public:
Location(int xx, int yy){
X = xx; Y = yy; cout << "Constructor Object.\n";
}
Location(const Location& obj){//copy构造函数
X = obj.X;
Y = obj.Y;
}
~Location(){
cout << X << "," << Y << " " << "Object destroyed." << endl;
}
int GetX(){ return X; }
int GetY(){ return Y; }
private:
int X;
int Y;
};
int _tmain(int argc, _TCHAR* argv[])
{
Location l1;//会报错 error C2512:“Location”:没有合适的默认构造函数可用
return 0;
}
// 构造函数使用规则.cpp : 定义控制台应用程序的入口点。
#include <iostream>
using namespace std;
class Location{
public:
Location(int xx=0, int yy=0){
X = xx; Y = yy; cout << "Constructor Object.\n";
}
Location(const Location& obj){//copy构造函数
X = obj.X;
Y = obj.Y;
}
~Location(){
cout << X << "," << Y << " " << "Object destroyed." << endl;
}
int GetX(){ return X; }
int GetY(){ return Y; }
private:
int X;
int Y;
};
int _tmain(int argc, _TCHAR* argv[])
{
Location l1;//不会报错
return 0;
}