一道对高手容易但对我很难的题:

bing_shan 2005-03-05 09:31:20
一个形状类,派生出长方形类和长方体类,然后求他们的面积和体积。怎么做呢?谢谢
...全文
188 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
bing_shan 2005-03-05
  • 打赏
  • 举报
回复
都是高手啊,我什么时候能这么厉害啊
onepence 2005-03-05
  • 打赏
  • 举报
回复
把二楼的代码改了一点点;)

#include "stdafx.h"
#include <iostream>
using namespace std;
class shape
{
public:
virtual int capability(){return 0;};

};

class rectangle:public shape
{
private:
int _x,_y;
public:
rectangle(int x,int y):_x(x),_y(y){}
int capability(){return _x*_y;}
};

class cuboid:public shape
{
private:
int _x,_y,_h;
public:
cuboid(int x,int y,int h):_x(x),_y(y),_h(h){}
int capability(){return _x*_y*_h;}
};

int main()
{
shape * rect=new rectangle(2,3);
shape * cb=new cuboid(2,3,4);
cout<<rect->capability()<<endl;

cout<<cb->capability()<<endl;
return 0;
}
Salam2001 2005-03-05
  • 打赏
  • 举报
回复
呵呵 现在诱惑别人近来看贴的标题花样可真多呀。
楼主下了不少工夫想出来的吧 呵呵

最后那个问题,那是名称空间。具体的,找google搜吧
bing_shan 2005-03-05
  • 打赏
  • 举报
回复
不好意思,请问using namespace std;是啥意思啊,谢谢
Dong 2005-03-05
  • 打赏
  • 举报
回复
大体这样,其他的自己修改到需要!虚函数按是有前缀virtual 的函数!


#include <iostream>
using namespace std;
class shape
{
};

class rectangle:public shape
{
private:
int _x,_y;
public:
rectangle(int x,int y):_x(x),_y(y){}
int acreage(){return _x*_y;}
};

class cuboid:public shape
{
private:
int _x,_y,_h;
public:
cuboid(int x,int y,int h):_x(x),_y(y),_h(h){}
int bulk(){return _x*_y*_h;}
};

int main()
{
rectangle rect(2,3);
cout<<rect.acreage()<<endl;
cuboid cb(2,3,4);
cout<<cb.bulk()<<endl;
return 0;
}
bing_shan 2005-03-05
  • 打赏
  • 举报
回复
什么是虚函数啊?
xfxf521 2005-03-05
  • 打赏
  • 举报
回复
先写一个形状类,分别写一个面积和体积的虚函数,在继承就够了!!
lzh1984 2005-03-05
  • 打赏
  • 举报
回复
用带虚拟函数的类的继承不就完了
hcj2002 2005-03-05
  • 打赏
  • 举报
回复
作业?
作业!

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧