版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_42187898/article/details/83627931
如果在阅读过程中发现有错误,望评论指正,希望大家一起学习,一起进步。
学习C++编译环境:Linux
第十八课 对象的构造(中)
1.构造函数
带有参数的构造函数
构造函数可以根据需要定义参数
一个类中可以存在多个重载的构造函数
构造函数的重载遵循C++重载的规则
友情提示
对象定义和对象声明不同
对象定义-申请对象的空间并调用构造函数
对象声明-告诉编译器存在这样一个对象
构造函数的自动调用—在定义对象时
18-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; // transfer Test()
Test t1(1); // transfer Test(int v)
Test t2 = 2; // transfer Test(int v)
int i(100);
printf("i = %d\n", i);
return 0;
}
运行结果
Test()
Test(int v), v = 1
Test(int v), v = 2
i = 100
在面向对象里面,两者存在差异
int i = 1; // 初始化—调用构造函数
int i; // i的初始值随机
i = 1; // 赋值
构造函数的调用
一般情况下,构造函数在对象定义时被自动调用
一些特殊情况下,需要手工调用构造函数
如何创建一个对象数组?
18-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 ta[3] = {Test(), Test(1), Test(2)};
for(int i=0; i<3; i++)
{
printf("ta[%d].getValue() = %d\n", i , ta[i].getValue());
}
Test t = Test(100);
printf("t.getValue() = %d\n", t.getValue());
return 0;
}
运行结果
v), v = 2
ta[0].getValue() = 0
ta[1].getValue() = 1
ta[2].getValue() = 2
Test(int v), v = 100
t.getValue() = 100
2.小实例
需求:开发一个数组类解决原生数组的安全性问题
提供函数获取数组长度
提供函数获取数组元素
提供函数设置数组元素
IntArray== 数组类==的实现 IntArray.cpp IntArray.h main.cpp
小结
构造函数可以根据需要定义参数
构造函数之间可以存在重载关系
构造函数遵循C++中重载函数的规则
对象定义时会触发构造函数的调用
在一些情况下可以手动调用构造函数