myvderived.cpp

来自「Visual C++高级编程及其项目应用开发(含源代码)」· C++ 代码 · 共 83 行

CPP
83
字号
#include <iostream>

using namespace std;

class CShape
{
public:
	CShape()
	{
		m_color=0;
	}
	~CShape(){};
	virtual void draw()
	{
		cout<<"This is a shape!"<<endl;
	}
	void SetColor(double n)
	{
		m_color =n;
		cout<<"My color is "<<m_color<<endl;
	}
private:
	double m_color;
};

class CRect :public CShape
{
public:
	CRect()
	{
		m_width = 5;
		m_height =4;
	};
	~CRect(){};
	double size()
	{
		return m_width * m_height;
	}
	void draw()
	{
		cout<<"This is a rect!"<<endl;
	}
private:
	double m_width, m_height;
};

class CCircle :public CShape
{
public:
	virtual void draw()
	{
		cout<<"This is a circle!"<<endl;
	}
};

void main()
{
	CShape	shp;
	CRect	rect;
	CCircle	circle;

	CShape	*pShape  =new CShape();
	CRect	*pRect =new CRect();

	//shp.size();//此处编译将会出错!
	//((CRect)shp).draw();//此处编译也行不同,
	//不能用CRect来强制转换基类对象的类型

	//((CShape*)pRect)->size();	//此句子编译出错!因为size()不是CShape的成员
	//((CShape*)pRect)->draw();	//这条语句将输出语句:“This is a rect!”
	//((CShape)rect).draw();		//这条语句将输出语句:“This is a shape!”

	pShape->draw();
	pShape =&rect;
	pShape->draw();
	/*pShape =&rect;

	pRect->draw();
	pShape->draw();

	pShape =&circle;
	pShape->draw();*/
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?