- 构造函数调用规则
1、创建一个类,C++编译器会给每个类都添加至少3个函数
(1)默认构造 (空实现)
(2)析构函数(空实现)
(3)拷贝构逍(值拷贝)
#include<iostream>
#include<string>
using namespace std;
//构造函数的调用规则
//1、创建一个类,C++编译器会给每个类都添加至少3个函数
//默认构造 (空实现)
//析构函数(空实现)
//拷贝构逍(值拷贝)
class Person
{
public:
//普通构造函数
Person()
{
cout << "Person 无参构造函数的调用" << endl;
}
Person(int age)
{
m_age = age;
cout << "Person 有参构造函数的调用" << endl;
}
//拷贝构造函数
/*Person(const Person &p)
{
m_age = p.m_age;
cout << "Person 拷贝构造函数的调用" << endl;
}*/
//析构函数
~Person()
{
cout << "Person 析构函数的调用" << endl;
}
int m_age;
};
void test01()
{
Person p1;
p1.m_age = 18;
//编译器提供的拷贝构造函数 值拷贝
Person p2(p1); //p2.m_age = 18;
cout << "p2的年龄为:" << p2.m_age << endl;
}
int main(){
test01();
cout << "***********test01************" << endl;
system("pause");
return 0;
}
2.1 如果我们写了有参构造函数,编译器就不再提供默认构造,依然提供拷贝构造函数
点击查看代码#include<iostream>
#include<string>
using namespace std;
//构造函数的调用规则
//1、创建一个类,C++编译器会给每个类都添加至少3个函数
//默认构造 (空实现)
//析构函数(空实现)
//拷贝构逍(值拷贝)
//2、如果我们写了有参构造函数,编译器就不再提供默认构造,依然提供拷贝构造
class Person
{
public:
//普通构造函数
/*Person()
{
cout << "Person 无参构造函数的调用" << endl;
}*/
Person(int age)
{
m_age = age;
cout << "Person 有参构造函数的调用" << endl;
}
//拷贝构造函数
/*Person(const Person &p)
{
m_age = p.m_age;
cout << "Person 拷贝构造函数的调用" << endl;
}*/
//析构函数
~Person()
{
cout << "Person 析构函数的调用" << endl;
}
int m_age;
};
void test02()
{
// Error:类"Person”不存在默认构造函数
//Person p3;
}
int main(){
test02();
cout << "***********test02************" << endl;
system("pause");
return 0;
}
点击查看代码
#include<iostream>
#include<string>
using namespace std;
//构造函数的调用规则
//1、创建一个类,C++编译器会给每个类都添加至少3个函数
//默认构造 (空实现)
//析构函数(空实现)
//拷贝构逍(值拷贝)
//2.1 如果我们写了有参构造函数,编译器就不再提供默认构造,依然提供拷贝构造
//2.2 如果我们写了拷贝构造函数,编译器就不再提供其他普通构造函数了
class Person
{
public:
Person(int age)
{
m_age = age;
cout << "Person 有参构造函数的调用" << endl;
}
//析构函数
~Person()
{
cout << "Person 析构函数的调用" << endl;
}
int m_age;
};
void test02()
{
// Error:类"Person”不存在默认构造函数
//Person p3;
Person p4(28);
Person p5(p4);
cout << "p5的年龄为:" << p5.m_age << endl;
}
int main(){
test02();
cout << "***********test02************" << endl;
system("pause");
return 0;
}
2.2 如果我们写了拷贝构造函数,编译器就不再提供其他普通构造函数了
点击查看代码#include<iostream>
#include<string>
using namespace std;
//构造函数的调用规则
//1、创建一个类,C++编译器会给每个类都添加至少3个函数
//默认构造 (空实现)
//析构函数(空实现)
//拷贝构逍(值拷贝)
//2.1 如果我们写了有参构造函数,编译器就不再提供默认构造,依然提供拷贝构造
//2.2 如果我们写了拷贝构造函数,编译器就不再提供其他普通构造函数了
class Person
{
public:
//拷贝构造函数
Person(const Person &p)
{
m_age = p.m_age;
cout << "Person 拷贝构造函数的调用" << endl;
}
//析构函数
~Person()
{
cout << "Person 析构函数的调用" << endl;
}
int m_age;
};
void test02()
{
//Error:类"Person”不存在默认构造函数
//Person p;
}
int main(){
test02();
cout << "***********test02************" << endl;
system("pause");
return 0;
}