编程论坛
注册
登录
编程论坛
→
C++教室
创建一个类,然后继承一个类,最后由这两个类生成对象,如何编程?
liuxue2010
发布于 2010-10-24 22:35, 555 次点击
各位大侠,目前遇到一难题,题目如下:创建一个类,然后继承一个类,然后由这两个类生成一个对象。
请高手给出程序,不甚感激!
3 回复
#2
a396280396
2010-10-25 20:04
class 类A{
.......
};
class 类B 继承方式:类A
{
.......
}
main()
{
A 对象a;
B 对象b;
}
#3
m21wo
2010-10-25 20:14
程序代码:
#include
<iostream>
using
namespace
std;
class
Shape
{
protected
:
double
length,width,area ;
public
:
Shape(
double
Leng,
double
Wid,
double
Area):length(Leng),width(Wid),area(Area)
{}
virtual
double
GetArea()
const
{
return
area;}
};
class
Rectangle :
public
Shape
{
public
:
Rectangle(
double
Leng=
0
,
double
Wid=
0
,
double
Area=
0
):Shape(Leng,Wid,area)
{ area=length*width;}
};
class
Triangle :
public
Shape
{
public
:
Triangle(
double
Leng=
0
,
double
Wid=
0
,
double
Area=
0
):Shape(Leng,Wid,area)
{area=length*width/
2
;}
};
int
main()
{
Rectangle r(
10
,
20
);
cout
<<r.GetArea()<<endl;
Triangle p(
90
,
45
);
cout
<<p.GetArea()<<endl;
}
简单的例子
#4
yzlovme
2010-10-26 17:46
父类:
class A
{
...........
};
子类:
class B public(private或protected):A
{
....................
}
int main()
{
A a;
B b;
.................
return 0;
}
1