一、CPP构造函数的核心知识点
二、几个关键知识点
1、普通基类定义了有参数的构造函数,派生类的构造函数必须给基类传参数使基类实现初始化。
2、派生类含有用const定义的数据成员,也要在参数列表中初始化。
3、参数列表的初始化顺序是先入基类,再到派生类;类内是根据数据定义的先后顺序初始化,与在列表中的先后顺序是没有必然关系的。
案例测试代码:
-
#include "stdafx.h"
-
#include
-
using namespace std;
-
class Vehicle
-
{
-
public:
-
//Vehicle(int width,int height)
-
Vehicle(int baseData):Height(baseData),Width(Height+baseData)
-
{
-
cout<<"Vehicle's Width=" }
-
public:
-
int Width;
-
int Height;
-
};
-
class Bus : public Vehicle
-
{
-
public:
-
Bus(int baseData,float price):Vehicle(baseData+SEQ_NUM),MAX_SPEED(100),mSeatCount(MAX_SPEED/5)
-
{
-
this->Price = price;
-
cout<<"Bus's Price=" <<",mSeatCount=" <<",MAX_SPEED="< <<",SEQ_NUM="< < }
-
public:
-
float Price;
-
private:
-
int mSeatCount;
-
const int MAX_SPEED;
-
static const int SEQ_NUM = 1001; //只有静态常量整型数据成员才能在类中初始化
-
};
-
-
int _tmain(int argc, _TCHAR* argv[])
-
{
-
Bus* myBus = new Bus(2,250000.0);
cout<<"MyBus's Width="<Width<<",Height="<Height<<",Price="<Price<
getchar();
return 0;
-
}
-
}
参考网址:
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
阅读(2891) | 评论(0) | 转发(0) |