c++构造函数主要分为三种:
#include <iostream>
using namespace std;
class Teacher
{
private:
char name[32];
int age;
public:
//有参构造函数
Teacher(int a)
{
age = a;
}
//无参构造函数
Teacher()
{
age = 33;
}
//拷贝构造函数
Teacher(const Teacher &p)
{
age = p.age;
}
{
private:
char name[32];
int age;
public:
//有参构造函数
Teacher(int a)
{
age = a;
}
//无参构造函数
Teacher()
{
age = 33;
}
//拷贝构造函数
Teacher(const Teacher &p)
{
age = p.age;
}
void GetTeacher()
{
cout << "age:" << age << endl;
}
//析构函数
~Teacher()
{
cout << "这里是析构函数~" << endl;
}
};
{
cout << "age:" << age << endl;
}
//析构函数
~Teacher()
{
cout << "这里是析构函数~" << endl;
}
};
void display()
{
//调用无参构造函数
Teacher t1;
t1.GetTeacher();
Teacher t1;
t1.GetTeacher();
//有参构造函数三种调用方法
//1. Teacher t2(36);
//2. Teacher t2 = Teacher(35);
//3. Teacher t2 = 36;
//t2.GetTeacher();
//1. Teacher t2(36);
//2. Teacher t2 = Teacher(35);
//3. Teacher t2 = 36;
//t2.GetTeacher();
//调用拷贝构造函数
Teacher t3 = t1;
t3.GetTeacher();
t3.GetTeacher();
}
int main()
{
display();
cout << "Hello world!" << endl;
return 0;
}
{
display();
cout << "Hello world!" << endl;
return 0;
}
当类中定义了拷贝构造函数时,c++编译器不会提供无参构造函数
当类中定义了有参构造函数时,c++编译器不会提供无参构造函数