一、案例代码及运行效果
- // Class_Construct_Seq.cpp : 定义控制台应用程序的入口点。
- //
- #include "stdafx.h"
- #include iostream>
- #include string>
- using namespace std; /* 没有std命名空间,cout,endl被标识为未声明 */
- class GrandPa
- {
- public:
- /* 注意!如果构造函数GrandPa不放在public区域,会被当成private成员 */
- GrandPa(char* s)
- //GrandPa(string s)
- {
- cout"I'm GrandPa,Created Successfully!"endl;
- coutsendlendl;
- };
- void DelegateShowText()
- {
- ShowText();
- }
- private:
- void ShowText()
- {
- cout"Print in GrandPa"endl;
- }
- }; /* 注意,类的声明后面还有一个分号*/
- class Son
- {
- public:
- Son()
- {
- cout"I'm Son,Created Successfully!"endlendl;
- }
- void ShowText()
- {
- cout"Print in Son"endl;
- }
- };
- //注意!多继承与父类的构造函数初始化都是使用逗号分开
- class GrandSon : public GrandPa,public Son
- {
- public:
- GrandSon():GrandPa("Vaule from GrandSon"),Son()
- {
- cout"I'm GrandSon,Created Successfully!"endlendl;
- }
- void ShowText()
- {
- cout"Print in GrandSon"endl;
- }
- };
- enum
- {
- GRANDPA = 1,
- SON,
- GRANDSON,
- };
- int main()
- {
- cout"-------------------------------------------------------"endl;
- cout"Select to create:"endl;
- cout"1 GrandPa ;"endl;
- cout"2 Son ;"endl;
- cout"3 GrandSon ;"endl;
- cout"-------------------------------------------------------"endl;
- int value = 0;
- cin >> value;
- GrandPa gPa("Value in GrandPa");
- Son s;
- GrandSon gSon;
- switch(value)
- {
- case GRANDPA:
- //gPa.ShowText(); 错误的用法,在main中调用GrandPa的私有成员,不允许!!
- gPa.DelegateShowText(); // 但可调用GrandPa的公有成员
- getchar();
- break;
- case SON:
- s.ShowText();
- getchar();
- break;
- case GRANDSON:
- gSon.ShowText();
- getchar();
- break;
- default:
- break;
- }
- getchar(); /* 用于屏幕输出暂停 */
- return 0;
- }
输出效果
图 派生类构造的过程
由上图,派生类的构造过程是先构造完基类,才进行自己构造。
二、代码与理论分析
上述CPP代码有几个注意点:
1、using namespace std; /* std命名空间,包含cout,endl的声明,必须写 */
2、class GrandPa{……}; ===>这里一定要有一个逗号
3、 注意!如果构造函数GrandPa不放在public区域,会被当成private成员
class GrandPa
{
public:
GrandPa(char* s)
……
}
4、多继承与派生类构造函数写法
(1)注意!多继承写法,父类间用逗号分开
class GrandSon : public GrandPa,public Son{};
(2)注意!派生类的构造函数需要依此给父类的构造函数传值(针对有参数的基类构造函数,没有参数的基类构造函数可以不写)
public:GrandSon():GrandPa("Vaule from GrandSon"),Son()
{
cout }
5、CPP枚举类型的写法:内部有逗号分开,结尾用分号
enum{
GRANDPA = 1,
SON,
GRANDSON,
};
6、不能通过main()调用GrandPa的私有方法,但可以调用其公有方法
//gPa.ShowText(); 错误的用法,在main中调用GrandPa的私有成员,不允许!!gPa.DelegateShowText(); // 但可调用GrandPa的公有成员
7、getchar(); 用于控制台的暂停
8、CPP输出字符串的方法
- GrandPa(char* s)
- //GrandPa(string s)
- {
- cout"I'm GrandPa,Created Successfully!"endl;
- coutsendlendl;
- };