本文学习自 狄泰软件学院 唐佐林老师的 C++课程
提炼1 带参数的构造函数的引入意义:可以使得每个对象拥有不同初始化状态
提炼2 对象的三种初始化方式
方式1:Test t = 100; //自动调用构造函数
方式2:Test t(100); //自动调用构造函数
方式3:Test t = Test(100); //手工调用构造函数的方式
实验1:构造函数的自动调用
实验2:构造函数的手动调用,创建对象数组
实验1:构造函数的自动调用
#include <stdio.h>
class Test
{
public:
Test()
{
printf("Test()\n");
}
Test(int v)
{
printf("Test(int v), v = %d\n", v);
}
};
int main()
{
Test t; // 调用 Test()
Test t1(1); // 调用 Test(int v)
Test t2 = 2; // 调用 Test(int v)
int i(100);// ==> int i = 100;
printf("i = %d\n", i);
return 0;
}
一般情况下 构造函数会在创建对象的时候被自动调用用于初始化对象,但是也有需要手动调用构造函数的情况,就是 创建对象数组的时候!!
实验2:构造函数的手动调用,创建对象数组
#include <stdio.h>
class Test
{
private:
int m_value;
public:
Test()
{
printf("Test()\n");
m_value = 0;
}
Test(int v)
{
printf("Test(int v), v = %d\n", v);
m_value = v;
}
int getValue()
{
return m_value;
}
};
int main()
{
//定义一个对象数组,自动调用构造函数
Test tb[3];
//结果是 对象数组中的每个对象的成员变量都为默认值,与大多数实际情况不符
for(int i=0; i<3; i++)
{
printf("tb[%d].getValue() = %d\n", i , tb[i].getValue());
}
/*创建 Test类的对象数组,手动调用构造函数
数组名 ta
数组大小:3个test对象
数组中每个元素:test对象
*/
Test ta[3] = {Test(), Test(1), Test(2)};
for(int i=0; i<3; i++)
{
printf("ta[%d].getValue() = %d\n", i , ta[i].getValue());
}
/*对象的初始化方式
方式1:Test t = 100;
方式2:Test t(100);
方式3:Test t = Test(100); //手工调用构造函数的方式
*/
Test t = Test(100);
printf("t.getValue() = %d\n", t.getValue());
return 0;
}
mhr@ubuntu:~/work/c++$ g++ 18-2.cpp
mhr@ubuntu:~/work/c++$ ./a.out
Test()
Test()
Test()
tb[0].getValue() = 0
tb[1].getValue() = 0
tb[2].getValue() = 0
Test()
Test(int v), v = 1
Test(int v), v = 2
ta[0].getValue() = 0
ta[1].getValue() = 1
ta[2].getValue() = 2
Test(int v), v = 100
t.getValue() = 100
mhr@ubuntu:~/work/c++$