C++构造函数详解:默认、参数化与拷贝构造函数
理解C++构造函数
本教程深入讲解C++构造函数——它们是什么、为何重要、如何实现默认、参数化和拷贝构造函数,附清晰示例。
构造函数是在对象实例化时自动运行的特殊成员函数。在C++中,构造函数与类同名且不指定返回类型。
class Wall {
public:
// Constructor
Wall() {
// initialization code
}
};
构造函数必须:
- 与类同名。
- 不声明返回类型。
- 可访问(通常为
public)。
默认构造函数
无参数的构造函数称为默认构造函数。上述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语言