c++类的构造函数

时间:2019-09-13
本文章向大家介绍c++类的构造函数,主要包括c++类的构造函数使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

类的构造函数

类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。

构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。

构造函数可用于为某些成员变量设置初始值。

下面为实例:

 1 #include<iostream>
 2 using namespace std;
 3 class Line
 4 {
 5 public:
 6     void setLength(double len);
 7     double getLength(void);
 8     Line();//为构造函数
 9 
10 private:
11     double length;
12 };
13 
14 //成员函数定义,包括构造函数
15 Line::Line(void)
16 {
17     cout << "Object is being created" << endl;
18 }
19 void Line::setLength(double len)
20 {
21     length = len;
22 }
23 double Line::getLength(void)
24 {
25     return length;
26 }
27 
28 //程序主函数
29 int main()
30 {
31     Line line;
32     //设置长度
33     line.setLength(6.0);
34     cout << "Length of line:" << line.getLength() << endl;
35     system("pause");
36     return 0;
37     
38 }

上述代码运行结果:

带参数的构造函数

默认的构造函数没有任何参数,但如果需要,构造函数也可以带有参数。这样在创建对象时就会给对象赋初始值,如下面的例子所示:

 1 #include <iostream>
 2  
 3 using namespace std;
 4  
 5 class Line
 6 {
 7    public:
 8       void setLength( double len );
 9       double getLength( void );
10       Line(double len);  // 这是构造函数
11  
12    private:
13       double length;
14 };
15  
16 // 成员函数定义,包括构造函数
17 Line::Line( double len)
18 {
19     cout << "Object is being created, length = " << len << endl;
20     length = len;
21 }
22  
23 void Line::setLength( double len )
24 {
25     length = len;
26 }
27  
28 double Line::getLength( void )
29 {
30     return length;
31 }
32 // 程序的主函数
33 int main( )
34 {
35    Line line(10.0);
36  
37    // 获取默认设置的长度
38    cout << "Length of line : " << line.getLength() <<endl;
39    // 再次设置长度
40    line.setLength(6.0); 
41    cout << "Length of line : " << line.getLength() <<endl;
42  
43    return 0;
44 }

上述代码运行结果如下所示:

使用初始化列表来初始化字段

使用初始化列表来初始化字段:

Line::Line( double len): length(len)
{
    cout << "Object is being created, length = " << len << endl;
}

也可写为:

Line::Line( double len)
{
    cout << "Object is being created, length = " << len << endl;
    length = len;
}

假设有一个类 C,具有多个字段 X、Y、Z 等需要进行初始化,同理地,您可以使用上面的语法,只需要在不同的字段使用逗号进行分隔,如下所示:

C::C( double a, double b, double c): X(a), Y(b), Z(c)
{
  ....
}

原文地址:https://www.cnblogs.com/Zzzzxy/p/11516478.html