构造函数 cpp

什么是构造函数

类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。

构造,那构造的是什么呢?

         构造成员变量的初始化值,内存空间等

构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。构造函数可用于 为某些成员变量设置初始值。 

无参构造函数

#include <iostream>
#include <string>
using namespace std; // 使用std命名空间
class Car {
public:
    string brand; // 不需要使用std::string
    int year;
    // 无参构造函数
    Car() {
        brand = "未知";
        year = 0;
        cout << "无参构造函数被调用" << endl; // 不需要使用std::cout和std::endl
    }
    void display() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};
int main() {
    Car myCar; // 创建Car对象
    myCar.display(); // 显示车辆信息
    return 0;
}

有参构造函数

#include <iostream>
#include <string>
using namespace std; // 使用std命名空间
class Car {
public:
    string brand; // 不需要使用std::string
    int year;
    // 有参构造函数
    Car(string b,int y) {
        brand = b;
        year = y;
        cout << "无参构造函数被调用" << endl; // 不需要使用std::cout和std::endl
    }
    void display() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};
int main() {
    Car myCar("HaiMa",2021); // 创建Car对象
    myCar.display(); // 显示车辆信息
    return 0;
}

使用初始化列表

在C++中,使用初始化列表来初始化类的字段是一种高效的初始化方式,

尤其在构造函数中。初始化列表 直接在对象的构造过程中初始化成员变量,而不是先创建成员变量后再赋值。这对于提高性能尤其重 要,特别是在涉及到复杂对象或引用和常量成员的情况下。

#include <iostream>
#include <string>
using namespace std; // 使用std命名空间
class Car {
public:
    string brand; // 不需要使用std::string
    int year;
 
    Car(string b,int c):brand(b),year(c) {

        cout << "构造函数被调用" << endl; // 不需要使用std::cout和std::endl
    }
    void display() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};
int main() {
    Car myCar("宾利",2021); // 创建Car对象
    myCar.display(); // 显示车辆信息
    return 0;
}

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值