2

C++ 构造函数实战指南:默认构造、带参数构造、拷贝构造与移动构造 - 小万哥丶

 1 month ago
source link: https://www.cnblogs.com/xiaowange/p/18151512
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C++ 构造函数

构造函数是 C++ 中一种特殊的成员函数,当创建类对象时自动调用。它用于初始化对象的状态,例如为属性分配初始值。构造函数与类同名,且没有返回值类型。

构造函数类型

C++ 支持多种类型的构造函数,用于满足不同的初始化需求:

  • 默认构造函数: 不带参数的构造函数,通常用于初始化对象的默认状态。
  • 带参数构造函数: 允许传入参数来初始化对象的状态。
  • 拷贝构造函数: 用于从另一个已存在的对象创建新对象。
  • 移动构造函数: 用于从即将销毁的临时对象转移资源到新对象。

默认构造函数

默认构造函数是最简单的构造函数,不接受任何参数。它通常用于为对象的属性设置默认值,或者执行简单的初始化操作。

class Person {public: string name; int age; Person() { // 默认构造函数 name = "Unknown"; age = 0; }}; int main() { Person p1; // 创建 Person 对象 cout << p1.name << ", " << p1.age << endl; // 输出:Unknown, 0 return 0;}

带参数构造函数

带参数构造函数允许传入参数来初始化对象的状态。参数可以是任何有效的 C++ 数据类型,包括基本类型、自定义类对象和指针。

class Car {public: string brand; string model; int year; Car(string b, string m, int y) { // 带参数构造函数 brand = b; model = m; year = y; }}; int main() { Car car1("Ford", "Mustang", 1967); // 创建 Car 对象并传入参数 cout << car1.brand << " " << car1.model << " " << car1.year << endl; // 输出:Ford Mustang 1967 return 0;}

拷贝构造函数

拷贝构造函数用于从另一个已存在的对象创建新对象。它通常用于复制另一个对象的属性值,而不共享原始对象的数据。

class Person {public: string name; int age; Person(const Person& other) { // 拷贝构造函数 name = other.name; age = other.age; }}; int main() { Person p1("Alice", 30); // 创建 Person 对象 Person p2(p1); // 拷贝构造函数创建 p2 cout << p2.name << ", " << p2.age << endl; // 输出:Alice, 30 return 0;}

移动构造函数

移动构造函数用于从即将销毁的临时对象转移资源到新对象。它通常用于避免不必要的资源复制,并提高性能。

class Person {public: string name; int age; Person(Person&& other) { // 移动构造函数 name = std::move(other.name); age = other.age; // 将 other 的资源转移到 this }}; int main() { Person p1("Bob", 25); // 创建 Person 对象 Person p2(std::move(p1)); // 移动构造函数创建 p2 cout << p2.name << ", " << p2.age << endl; // 输出:Bob, 25 cout << p1.name << ", " << p1.age << endl; // 输出:, 0 (p1 的资源已转移) return 0;}

构造函数的访问控制

构造函数的访问权限可以使用访问控制修饰符来控制,例如 publicprivateprotected

  • public:构造函数可以在类外部的任何地方调用。
  • private:构造函数只能在类的内部调用。
  • protected:构造函数可以在类的内部或其子类中调用。

构造函数是 C++ 中重要的面向对象编程机制,用于初始化和管理对象的状态。通过理解不同类型的构造函数及其用法,您可以创建健壮且可维护的 C++ 代码。

为了方便其他设备和平台的小伙伴观看往期文章:

微信公众号搜索:Let us Coding,关注后即可获取最新文章推送

看完如果觉得有帮助,欢迎点赞、收藏、关注


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK