目录
1. 构造函数
1.1 基本使用
构造函数是一种特殊的成员函数,用于创建对象时初始化,写法上有以下要求:
● 函数名称必须与类名完全相同。
● 构造函数不写返回值
● 如果程序员不手动编写构造函数,编译器会自动添加一个默认无参的构造函数。

● 手动添加构造函数后,编译器就不会自动添加默认无参构造函数了。
● 构造函数在创建对象时,常用于给对象的属性赋予初始值。
● 构造函数也支持构造函数重载
● 也支持函数参数默认值
利用构造函数赋初值:
无参构造函数创建对象时:在构造函数内进行默认值进行初始化,
有参构造函数创建对象时,通过传入的参数进行初始化。
#include <iostream>
using namespace std;
// 构造函数---
class MoblePhone1
{
private:
string bread;
string model;
int weight = 200;
public: // 权限:最开放的权限
MoblePhone1() // 无参
{
bread = "8848";
model = "鳄鱼皮";
weight = 5500;
cout << "无参构造函数被调用了" << endl;
}
MoblePhone1(string b,string m,int w) // 有参
{
bread = b;
model = m;
weight = w;
cout << "有参构造函数被调用了" << endl;
}
string get_bread()
{
return bread;
}
void set_bread(string b)
{
bread = b;
}
string get_model()
{
return model;
}
void set_model(string c)
{
model = c;
}
int get_weight()
{
return weight;
}
};
int main()
{
// 构造函数
// 栈内存
cout << "栈内存,无参" << endl;
MoblePhone1 mp3; // 无参
cout << mp3.get_bread() << endl;
cout << mp3.get_model() << endl;
cout << mp3.get_weight() << endl;
cout << endl;
cout << "栈内存,有参" << endl;
MoblePhone1 mp4("小米","14Pro", 500); // 有参
cout << mp4.get_bread() << endl;
cout << mp4.get_model() << endl;
cout << mp4.get_weight() << endl;
cout << endl;
// 堆内存
cout << "堆内存,无参" << endl;
MoblePhone1 *mp5 = new MoblePhone1; // 无参
cout << mp5->get_bread() << endl;
cout << mp5->get_model() << endl;
cout << mp5->get_weight() << endl;
cout << endl;
cout << "堆内存,有参" << endl;
MoblePhone1 *mp6 = new MoblePhone1("红米","70ulurt",500); // 有参
cout << mp6->get_bread() << endl;
cout &

最低0.47元/天 解锁文章
3079

被折叠的 条评论
为什么被折叠?



