类与对象之函数调用规则


默认情况下,C++编译器至少给一个类添加3个函数

  1. 默认构造函数(无参,函数体为空)
  2. 默认析构函数(无参,函数体为空)
  3. 默认拷贝构造函数;对属性进行拷贝

构造函数调用规则如下

  • 如果用户定义有参构造函数c++不在提供默认无参构造函数,但是会提供默认拷贝构造
  • 如果用户定义默认拷贝函数,c++不会在通过其他构造函数

举个栗子

class Person
{
public:

Person() {
cout << "默认构造函数。\n";
}
Person(int a)
{
age = a;
cout << "有参构造函数。\n";
cout <<"年龄:"<< age<<endl;
}
//Person(const Person& p)
//{
// cout << "拷贝构造函数。\n";
// age = p.age;

//}
~Person()
{
cout << "析构函数。\n";
}

int age;
};
int main()
{
Person p;
p = 10;
return 0;
}
默认构造函数。
有参构造函数。
年龄:10
析构函数。
析构函数。

Author: T1g3r
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source T1g3r !
评论
  TOC