亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

C++构造函数详解:默认、参数化与拷贝构造函数

理解C++构造函数

本教程深入讲解C++构造函数——它们是什么、为何重要、如何实现默认、参数化和拷贝构造函数,附清晰示例。

构造函数是在对象实例化时自动运行的特殊成员函数。在C++中,构造函数与类同名且不指定返回类型。

class Wall { 
public: 
    // Constructor 
    Wall() { 
        // initialization code 
    } 
};

构造函数必须:


默认构造函数

无参数的构造函数称为默认构造函数。上述Wall()即为一例。


示例1:默认构造函数

// 演示默认构造函数 
#include <iostream> 
using namespace std; 
class Wall { 
private: 
    double length; 
public: 
    // Default constructor 
    Wall() { 
        length = 5.5; 
        cout << "Creating a wall." << endl; 
        cout << "Length = " << length << endl; 
    } 
}; 
int main() { 
    Wall wall1; 
    return 0; 
}

输出

Creating a Wall 
Length = 5.5

实例化wall1时,默认构造函数将length设为5.5并打印信息。

注意:若类缺显式构造函数,编译器自动生成不执行任何操作的默认构造函数。


参数化构造函数

参数化构造函数接收参数,在对象创建时初始化成员数据。它们是设置对象状态的首选方式。


示例2:参数化构造函数

// 使用参数化构造函数计算墙面积 
#include <iostream> 
using namespace std; 
class Wall { 
private: 
    double length; 
    double height; 
public: 
    // Parameterized constructor 
    Wall(double len, double hgt) { 
        length = len; 
        height = hgt; 
    } 
    double calculateArea() { 
        return length * height; 
    } 
}; 
int main() { 
    Wall wall1(10.5, 8.6); 
    Wall wall2(8.5, 6.3); 
    cout << "Area of Wall 1: " << wall1.calculateArea() << endl; 
    cout << "Area of Wall 2: " << wall2.calculateArea(); 
    return 0; 
}

输出

Area of Wall 1: 90.3 
Area of Wall 2: 53.55

构造函数将传入值赋给length和height,使calculateArea()能计算墙面积。


拷贝构造函数

拷贝构造函数创建新对象作为现有对象的精确副本。当对象用同类型另一对象初始化时调用。


示例3:拷贝构造函数

#include <iostream> 
using namespace std; 
class Wall { 
private: 
    double length; 
    double height; 
public: 
    // Parameterized constructor 
    Wall(double len, double hgt) { 
        length = len; 
        height = hgt; 
    } 
    // Copy constructor 
    Wall(Wall &obj) { 
        length = obj.length; 
        height = obj.height; 
    } 
    double calculateArea() { 
        return length * height; 
    } 
}; 
int main() { 
    Wall wall1(10.5, 8.6); 
    Wall wall2 = wall1; // 调用拷贝构造函数 
    cout << "Area of Wall 1: " << wall1.calculateArea() << endl; 
    cout << "Area of Wall 2: " << wall2.calculateArea(); 
    return 0; 
}

输出

Area of Wall 1: 90.3 
Area of Wall 2: 90.3

拷贝构造函数从wall1复制length和height到wall2,确保两对象状态相同。

注意:构造函数主要初始化对象,但也使自定义逻辑在对象创建时运行。

C语言

  1. C# 构造函数:类型、示例与高级模式完全指南
  2. 掌握 C# 构造函数重载:灵活创建对象的多种姿势
  3. 深入理解 C++ 数据类型:基础类型、修饰符与最佳实践
  4. 掌握 C++ 运算符:六大类型全解析与实战示例
  5. C++ 注释最佳实践:编写可读、可维护代码的注释艺术
  6. C++ 类模板实战指南:编写灵活的类型无关代码
  7. C++编程语言:核心特性全景解析
  8. C++常量与字面量完全手册:类型、语法与最佳实践
  9. C++运算符大全:算术/关系/逻辑/位/赋值/杂项与优先级结合性
  10. C++数值类型实战指南:基本类型、数学函数与随机数生成
  11. 精通 Java 构造器:类型、用法与实战示例
  12. 理解 Java 构造器:初始化与最佳实践