C++:类的继承例题

类的继承

C++:类的继承例题_第1张图片

#include "stdafx.h"
#include 
using namespace std;

class Animal {
	//int age;如果不加pulic:那么系统会自动默认为private
public:
	int age;
};

class Dog : Animal {
public:
	void SetAge(int n) {age = n;}
};

int main()
{
	Dog d;
	d.SetAge(2);
	return 0;
}

C++:类的继承例题_第2张图片

#include "stdafx.h"
#include 
using namespace std;

class BaseClass {
public:
	int Number;
	int getNumber() {return Number;}
	BaseClass(){ cout<<"BaseClass construct"<<endl;}
	~BaseClass(){ cout<<"BaseClass destruct"<<endl;}
};

class DerivedClass : BaseClass {
public:
	DerivedClass() {
		Number = 0;
		Number ++;
		cout << "DerivedClass Construction. Number = " << getNumber() << endl;
	}
	~DerivedClass() {
		Number --;
		cout << "DerivedClass Destruction. Number = " << getNumber() << endl;
	}
};

int main()
{
	DerivedClass d;
	return 0;
}

C++:类的继承例题_第3张图片

#include "stdafx.h"
#include 
using namespace std;

class Vehicle
{
public:
	int MaxSpeed;
	int Weight;
	void Run(){cout<<"Vehicle run"<<endl;};
	void Stop(){cout<<"Vehicle stop"<<endl;};
};

class Bicycle : virtual public Vehicle//如果不设置成虚基类则会出现二义性
{
public:
	int Height;
};

class Motorcar : virtual public Vehicle
{
public:
	int SeatNum;
};

class Motorcycle : public Bicycle, public Motorcar
{ };

int main()
{
	Motorcycle m;

	m.Height=1;
	m.SeatNum=2;
	m.Weight=100;
	m.MaxSpeed=60;
	
	m.Run();
	m.Stop();

	return 0;
}

注释 :如果以普通方式公有继承vehicle那么在bicycle和motorcar中都有一份基类成员的拷贝,而bicycle和motorcar共同派生出motorcycle后,motorcycle对于从vehicle中的成员有两份拷贝,系统无法知道是两份拷贝中的哪一个
C++:类的继承例题_第4张图片

你可能感兴趣的:(C++,c++)