加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c++类的构造函数

发布时间:2020-12-16 09:15:58 所属栏目:百科 来源:网络整理
导读:类的构造函数 类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。 构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。 构造函数可用于为某些成员变量设置初始值。 下面为实例: 1 #includeiostream 2 us

类的构造函数

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

构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 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)
{
  ....
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读