C++ 构造函数
构造函数
C++ 中的构造函数是一种 特殊方法,它在创建类的对象时自动调用。
要创建构造函数,请使用与类相同的名称,后跟括号():
实例
#include <iostream>using namespace std;class MyClass { // The classpublic: // Access specifierMyClass() { // Constructorcout << "Hello World!";}};int main() {MyClass myObj; // Create an object of MyClass (this will call the constructor)return 0;}
注意:构造函
数与类具有相同的名称,它始终是public 公共的,并且没有任何返回值。
构造函数参数
构造函数还可以获取参数(就像常规函数一样),这对于设置属性的初始值非常有用。
下面的类具有 brand 品牌、model 型号和 year 年份属性,以及具有不同参数的构造函数。在构造函数中,我们将属性设置为构造函数参数(brand=x等)。当我们调用构造函数(通过创建类的对象)时,我们将参数传递给构造函数,构造函数将相应属性的值设置为相同的值:
实例
#include <iostream>using namespace std;class Car { // The classpublic: // Access specifierstring brand; // Attributestring model; // Attributeint year; // AttributeCar(string x, string y, int z) { // Constructor with parametersbrand = x;model = y;year = z;}};int main() {// Create Car objects and call the constructor with different valuesCar carObj1("BMW", "X5", 1999);Car carObj2("Ford", "Mustang", 1969);// Print valuescout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";return 0;}
与函数一样,构造函数也可以在类之外定义。首先,在类内声明构造函数,然后在类外定义它,方法是指定类的名称,后跟作用域运算符 ::,后跟构造函数的名称(与类相同):
实例
#include <iostream>using namespace std;class Car { // The classpublic: // Access specifierstring brand; // Attributestring model; // Attributeint year; // AttributeCar(string x, string y, int z); // Constructor declaration};// Constructor definition outside the classCar::Car(string x, string y, int z) {brand = x;model = y;year = z;}int main() {// Create Car objects and call the constructor with different valuesCar carObj1("BMW", "X5", 1999);Car carObj2("Ford", "Mustang", 1969);// Print valuescout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";return 0;}