C++之 构造函数调用规则

来源:互联网 发布:画框图软件 编辑:程序博客网 时间:2024/05/18 18:55

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;}



0 0
原创粉丝点击