myderived.cpp

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

CPP
67
字号
#include <iostream>

using namespace std;

class CShape
{
public:
	CShape()
	{
		m_color=0;
	}
	~CShape(){};
	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;
};

void main()
{
	CShape	shp;
	CRect	rect;

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

	pShape=&rect;
	cout<<rect.size()<<endl; //正确执行,并得出计算结果
	cout<<pShape->size()<<endl; //错误,因为size()函数不是CShape类的方法
	
	//pRect =(CRect*)pShape;

	//pRect->draw();
	//pShape->draw();
	/*shp.draw();
	rect.draw();
	shp.SetColor(5);
	rect.SetColor(8);*/
}

⌨️ 快捷键说明

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