这是一个涉及继承的简单C ++程序 [英] This is a simple program of C++ involving inheritence
本文介绍了这是一个涉及继承的简单C ++程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习继承,当我执行这个程序时,我得不到正确的输出。 Plz帮助。
我尝试过:
#include iostream.h
class 变量
{
public :
// square
int a;
// rect
int l,b;
};
class square: public variables
{
public :
void s()
{
cout<< 你选择了正方形。输入正方形的一边。\ n;
cin>> a;
}
};
class rectangle: public variables
{
public :
void r()
{
cout<< 您选择了矩形。输入矩形的长度和宽度。\ n;
cin>> l>> b;
}
};
class 计算: public 变量
{
public :
void as() // as = square of square
{
cout<< a * a;
}
void ar() // ar =矩形区域
{
cout<< l * b;
}
void ps() // ps =正方形的周长
{
cout<< 4 * a;
}
void pr() // pr =矩形的周长
{
cout<<( 2 * l + 2 * b);
}
};
int main()
{
计算obj;
平方q;
矩形t;
int n;
cout<< 欢迎来到数学页面\ n;
cout<< 选择形状\ n;
cout<< \ n1)Square \\\
2)Rectangle(1-2)\ N跨度>;
cin>> n;
switch (n)
{
case 1 :qs();
cout<< square的面积=;
obj.as();
cout<< square的周长=;
obj.ps();
break ;
case 2 :t.r();
cout<< 矩形区域=;
obj.ar();
cout<< 矩形的周长=;
obj.pr();
break ;
}
return 0 ;
}
解决方案
如果你仔细阅读你的代码,你会看到它:在这两种情况下你都给出了相同的输出突击队。
制作关于遗产的一些图画。我猜你的计算应该从矩形继承,但不能直接从变量继承。
提示:学会使用指针,然后继承和类型转换变得有趣。
I am learning inheritance and when I executed this program I am not getting right outputs. Plz help.
What I have tried:
#include "iostream.h"
class variables
{
public:
//square
int a;
//rect
int l,b;
};
class square : public variables
{
public:
void s()
{
cout<<"You chose square. Enter the side of the square. \n";
cin>>a;
}
};
class rectangle : public variables
{
public:
void r()
{
cout<<"You chose rectangle. Enter the length and breadth of the rectangle. \n";
cin>>l>>b;
}
};
class calculate : public variables
{
public:
void as() //as=area of square
{
cout<<a*a;
}
void ar() //ar=area of rectangle
{
cout<<l*b;
}
void ps() //ps=perimeter of square
{
cout<<4*a;
}
void pr() //pr=perimeter of rectangle
{
cout<<(2*l+2*b);
}
};
int main()
{
calculate obj;
square q;
rectangle t;
int n;
cout<<"Welcome to the maths page\n";
cout<<"Choose the shape\n";
cout<<"\n1) Square \n2) Rectangle (1-2)\n";
cin>>n;
switch (n)
{
case 1: q.s();
cout<<"Area of the square = ";
obj.as();
cout<<"Perimeter of the square = ";
obj.ps();
break;
case 2: t.r();
cout<<"Area of the rectangle = ";
obj.ar();
cout<<"Perimeter of the rectangle = ";
obj.pr();
break;
}
return 0;
}
解决方案
If you read your code carefully you would see it: in both cases you give the same output commandos.
Make some drawing about the inheritence. I guess your calculate should inheritance from rectangle, but not directly from variable.
Tip: learn to work with pointers, then inheritance and type casting gets interesting.
这篇关于这是一个涉及继承的简单C ++程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文