cloud-2014的专栏

知识在于分享!!!

C++基础学习(六),继承

#include <iostream>
#include <string>

using namespace std;

class Fish
{
public:
	void Swim()
	{
		if (m_bFreshWaterFish)
		{
			cout<<"swims in lake"<<endl;
		}
		else
		{
			cout<<"swims in sea"<<endl;
		}
	}

protected:
	bool m_bFreshWaterFish;
};

class Tuna : public Fish
{
public:
	Tuna()
	{
		m_bFreshWaterFish = false;
	}
};

class Carp : public Fish
{
public:
	Carp()
	{
		m_bFreshWaterFish = true;
	}
};

int main()
{
	Tuna tuna;
	Carp carp;
	tuna.Swim();
	carp.Swim();

	system("pause");
	return 0;
}


#include <iostream>
#include <string>

using namespace std;

class Fish
{
public:
	Fish(bool isFreshWater)
		:m_bFreshWaterFish(isFreshWater)
	{

	}

	void Swim()
	{
		if (m_bFreshWaterFish)
		{
			cout<<"Swims in lake"<<endl;
		}
		else
		{
			cout<<"Swims in sea"<<endl;
		}
	}

protected:
	bool m_bFreshWaterFish;
};

class Tuna : public Fish
{
public:
	Tuna(bool isFreshWater)
		:Fish(isFreshWater)
	{

	}
};

class Carp : public Fish
{
public:
	Carp(bool isFreshWater)
		:Fish(isFreshWater)
	{

	}
};

int main()
{
	Tuna tuna(false);
	Carp carp(true);
	tuna.Swim();
	carp.Swim();

	system("pause");
	return 0;
}

#include <iostream>
#include <string>

using namespace std;

class FishDummyMember
{
public:
	FishDummyMember()
	{
		cout<<"call FishDummyMember() "<<endl;
	}

	~FishDummyMember()
	{
		cout<<"call ~FishDummyMember() "<<endl;
	}
};

class Fish
{
public:
	Fish()
	{
		cout<<"call Fish() "<<endl;
	}

	~Fish()
	{
		cout<<"call ~Fish() "<<endl;
	}

protected:
	FishDummyMember dummy;
};

class TunaDummyMember
{
public:
	TunaDummyMember()
	{
		cout<<"call TunaDummyMember() "<<endl;
	}

	~TunaDummyMember()
	{
		cout<<"call ~TunaDummyMember() "<<endl;
	}
};

class Tuna : public Fish
{
public:
	Tuna()
	{
		cout<<"call Tuna() "<<endl;
	}

	~Tuna()
	{
		cout<<"call ~Tuna() "<<endl;
	}

private:
	TunaDummyMember dummy;
};

//基类,派生类及其成员的构造和析构顺序测试
int main()
{
	Tuna tuna;

	//system("pause");
	return 0;
}


#include <iostream>
#include <string>

using namespace std;

class Base
{
public:
	void func()
	{
		cout<<"call Base.func()"<<endl;
	}
};

class Sub : private Base
{
public:
	void callFunc()
	{
		func();
	}
};

//类的私有继承测试,只有派生类可以调用基类的方法,派生类的对象不能调
int main()
{
	Sub sub;
	sub.callFunc();

	//error C2247: “Base::func”不可访问,因为“Sub”使用“private”从“Base”继承
	sub.func();

	system("pause");
	return 0;
}






阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012592062/article/details/80342998
个人分类: C++基础
想对作者说点什么? 我来说一句

类的继承练习

2013年06月17日 7KB 下载

没有更多推荐了,返回首页

不良信息举报

C++基础学习(六),继承

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭