一、CPP构造函数的核心知识点

简介: 一、CPP构造函数的核心知识点 二、几个关键知识点 1、普通基类定义了有参数的构造函数,派生类的构造函数必须给基类传参数使基类实现初始化。 2、派生类含有用const定义的数据成员,也要在参数列表中初始化。

一、CPP构造函数的核心知识点

二、几个关键知识点

1、普通基类定义了有参数的构造函数,派生类的构造函数必须给基类传参数使基类实现初始化。

2、派生类含有用const定义的数据成员,也要在参数列表中初始化。

3、参数列表的初始化顺序是先入基类,再到派生类;类内是根据数据定义的先后顺序初始化,与在列表中的先后顺序是没有必然关系的。

案例测试代码:


  1. #include "stdafx.h"
  2. #include
  3. using namespace std;
  4. class Vehicle
  5. {
  6. public:
  7.     //Vehicle(int width,int height)
  8.     Vehicle(int baseData):Height(baseData),Width(Height+baseData)
  9.     {
  10.         cout"Vehicle's Width=" }
  11. public:
  12.     int Width;
  13.     int Height;
  14. };
  15. class Bus : public Vehicle
  16. {
  17. public:
  18.     Bus(int baseData,float price):Vehicle(baseData+SEQ_NUM),MAX_SPEED(100),mSeatCount(MAX_SPEED/5)
  19.     {
  20.         this->Price = price;
  21.         cout"Bus's Price=" ",mSeatCount=" ",MAX_SPEED=" ",SEQ_NUM=" }
  22. public:
  23.     float Price;
  24. private:
  25.     int mSeatCount;
  26.     const int MAX_SPEED;
  27.     static const int SEQ_NUM = 1001; //只有静态常量整型数据成员才能在类中初始化
  28. };

  29. int _tmain(int argc, _TCHAR* argv[])
  30. {
  31.     Bus* myBus = new Bus(2,250000.0);
        coutWidthHeightPrice     getchar();
        return 0;
  32. }
  33. }




参考网址:

http://blog.163.com/xychenbaihu@yeah/blog/static/132229655201243110342683/

http://www.cnblogs.com/BlueTzar/articles/1223169.html

http://blog.csdn.net/zhaojinjia/article/details/8785912

相关文章
|
1月前
|
编译器 C语言 C++
【C++专栏】C++入门 | 类和对象 | 类的引入、struct&class的区别、类的定义
【C++专栏】C++入门 | 类和对象 | 类的引入、struct&class的区别、类的定义
13 0
|
2月前
|
存储 C++
CPP的类和对象
CPP的类和对象
16 1
|
5月前
|
存储 C++
[C++ 从入门到精通] 7.类基础、成员函数、对象拷贝
[C++ 从入门到精通] 7.类基础、成员函数、对象拷贝
26 0
|
10月前
|
10月前
|
芯片
CPP2022-24-类与对象(下)
CPP2022-24-类与对象
64 0
|
前端开发
前端学习案例2-拷贝继承2
前端学习案例2-拷贝继承2
30 0
前端学习案例2-拷贝继承2
|
前端开发
前端学习案例1-拷贝继承
前端学习案例1-拷贝继承
39 0
前端学习案例1-拷贝继承
MFC CFileFind类用法总结
MFC CFileFind类用法总结
338 0