构造函数是初始化类对象的类的特殊成员函数。构造函数名称与类名称相同,并且没有返回类型。让我们举一个简单的例子来理解构造函数的工作原理。
简单示例:如何在 C++ 中使用构造函数
阅读以下程序中的注释,以了解该程序的每个部分。
#include <iostream>using namespace std;class constructorDemo{public: int num; char ch; /* This is a default constructor of the * class, do note that it's name is same as * class name and it doesn't have return type. */ constructorDemo() { num = 100; ch = 'A'; }};int main(){ /* This is how we create the object of class, * I have given the object name as obj, you can * give any name, just remember the syntax: * class_name object_name; */ constructorDemo obj; /* This is how we access data members using object * we are just checking that the value we have * initialized in constructor are reflecting or not. */ cout<<"num: "<<obj.num<<endl; cout<<"ch: "<<obj.ch; return 0;}输出:
num: 100ch: A
构造函数与成员函数
现在我们知道什么是构造函数,让我们讨论构造函数与类的成员函数的不同之处。
1)构造函数没有返回类型。成员函数具有返回类型。
2)当我们创建类的对象时,会自动调用构造函数。需要使用类的对象显式调用成员函数。
3)当我们不在我们的类中创建任何构造函数时,C++ 编译器生成一个默认构造函数并将其插入到我们的代码中。这同样适用于成员函数。
这是编译器生成的默认构造函数的外观:
class XYZ{ .... XYZ() { //Empty no code }};C++ 中构造函数的类型
C++ 中有两种类型的构造函数。 1)默认构造函数 2)参数化构造函数
默认构造函数
默认构造函数没有任何参数(或参数)。
#include <iostream>using namespace std;class Website{public: //Default constructor Website() { cout<<"Welcome to BeginnersBook"<<endl; }};int main(void){ /*creating two objects of class Website. * This means that the default constructor * should have been invoked twice. */ Website obj1; Website obj2; return 0;}输出:
Welcome to BeginnersBookWelcome to BeginnersBook
如果未在类中指定任何构造函数,则编译器将在代码中插入没有代码(空体)的默认构造函数。
参数化构造函数
带参数的构造函数称为参数化构造函数。这些类型的构造函数允许我们在创建对象时传递参数。让我们看看他们的样子:
让我们假设类名是XYZ。
默认构造函数:
XYZ() {}....XYZ obj;....参数化构造函数:
XYZ(int a, int b) {}...XYZ obj(10, 20);例:
#include <iostream>using namespace std;class Add{public: //Parameterized constructor Add(int num1, int num2) { cout<<(num1+num2)<<endl; }};int main(void){ /* One way of creating object. Also * known as implicit call to the * constructor */ Add obj1(10, 20); /* Another way of creating object. This * is known as explicit calling the * constructor. */ Add obj2 = Add(50, 60); return 0;}输出:
30110
