在本教程中,我们将学习以下不同类型的构造函数:
- 默认构造函数
- 参数化构造函数
- 重载构造函数
- 具有默认参数的构造函数
1.默认构造函数:
- 不带任何参数的构造函数称为默认构造函数。
- 创建对象时,将调用默认构造函数。
- 默认构造函数不能重载,因为它不带任何参数。
- 如果在类中没有定义默认的构造函数,则编译器将创建一个。
- 当我们要在创建对象时使用相同的值初始化所有数据成员时,默认构造函数很有用。
- 构造函数应始终公开。
例:
#include<iostream> using namespace std; class Ex { public: Ex() { cout<<"默认构造函数 is called"<<endl; } }; int main() { Ex e; return 0; }
输出:
默认构造函数 is called
2.参数化的构造函数
如前所述,我们可以重载构造函数。因此,我们可以创建接受参数的构造函数。因此,在创建对象时,我们应该将参数传递给那些对象。
参数化的构造函数:
- 接受参数的构造函数称为参数化构造函数。
- 它们可能会过载。
- 当我们需要用不同的值初始化不同的对象时使用它们。
- 它们可以具有默认值。
- 如果定义参数化的构造函数,则编译器不会创建默认构造函数。
参数化构造函数可以通过2种类型来调用。
- 隐式呼叫
- 明确呼叫
#include<iostream> using namespace std; class Ex { private: int a; int b; public: Ex(int x, int y) { a = x; b = y; cout<<"Parameterized Constructor is called"<<endl; } void display() { cout<<"The value of a = "<<a<<" The value of b = "<<b<<endl; } }; int main() { Ex e(10, 20); //Implicit call e.display(); Ex e1 = Ex(20, 30); //Explicit call e1.display(); return 0; }
输出:
Parameterized Constructor is called The value of a = 10 The value of b = 20 Parameterized Constructor is called The value of a = 20 The value of b = 30
3.重载构造函数
类似的函数构造函数也可以重载。以下是相同的示例。
/* * File : constructor_overloading.cpp * Author : [email protected] * Copyright: @ 前开发者教程.com */ #include<iostream> using namespace std; class Example { int num; public: Example(); Example(int a); void display(); }; Example :: Example() { cout<<"默认构造函数"<<endl; } Example :: Example(int a) { num = a; cout<<"Parameterized Constructor num value is = "<<num<<endl; } int main() { Example e1; Example e2(10); return 0; }
输出:
默认构造函数 Parameterized Constructor num value is = 10
4.具有默认参数的构造函数。
像函数一样,构造函数也可以具有默认参数。相同的规则作为函数默认参数适用。
例:
/* * File : constructor_Default_arguments.cpp * Author : [email protected] * Copyright: @ 前开发者教程.com */ #include<iostream> using namespace std; class Example { int num_1; int num_2; public: Example(int a, int b = 30); void display(); }; Example :: Example(int a, int b) { num_1 = a; num_2 = b; } void Example :: display() { cout<<"num_1 value is = "<<num_1 <<" and num_2 is = " << num_2<<endl; } int main() { Example e2(10); e2.display(); return 0; }
输出:
num_1 value is = 10 and num_2 is = 30
6. C ++中的构造函数初始化器列表
初始化程序列表用于初始化类的成员。
下面的示例显示了一种简单的方法:
#include<iostream> using namespace std; class MyClass{ int num1; int num2; public: MyClass(int a, int b):num1(a), num2(b){ } /* MyClass(int a, int b) { num1 = a; num2 = b; } */ }; int main(){ MyClass obj(10, 20); }
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |