类的对象初始化
1. 显示初始化
class Test
{
public:
void init(int mya)
{
a = mya;
}
protected:
private:
int a;
};
void main()
{
Test t1;
t1.init(10);
system("pause");
}
缺点:如果定义一个类数组,初始化比较麻烦Test array[100];
2. 构造函数初始化
- 2.1 无参构造函数(默认构造函数)初始化
- 2.2 带参数的构造函数初始化
//带参数的构造函数的三种应用方法
Test t1(10); //c++编译器自动调用有参数的构造函数
Test t2 = 16; //c++编译器自动调用有参数的构造函数
- 2.3 拷贝构造函数(赋值构造函数)初始化
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
a = 10;
}
Test(int mya)
{
a = mya;
}
Test(const Test &obj)
{
}
protected:
private:
int a;
};
void main()
{
Test t1(10);
Test t2 = 16;
Test t3 = Test(12);
system("pause");
}