在C++中学习OOPS概念时,我遇到了本教程链接。 http://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm使用Constructor参数实例化一个类对象与不带参数的*运算符之间的区别C++
在基类Shape
,它有两个参数来设置其受保护的变量和main()
我想创建一个对象Shape
类的唯一方法是通过执行类似Shape shape(2,4)
给构造Shape
类匹配的构造。
有人可以说实例化Shape *shape
没有任何参数的工作和创建对象之间的差异是什么Shape shape(2,4)
和Shape *shape
。
#include <iostream>
using namespace std;
class Shape{
protected:
int w,h;
public:
Shape(int a, int b){
w=a;
h=b;
}
int area(){
cout << "Shape class area" << endl;
return 0;
}
};
class Rect:public Shape{
public:
Rect(int a, int b):Shape(a,b) {}
int area(){
cout <<"Rect class area " << endl;
return w*h;
}
};
class Tri:public Shape{
public:
Tri(int a, int b):Shape(a,b) {}
int area(){
cout << "Tri class area" << endl;
return (w*h)/2;
}
};
int main(){
Shape *shape;
Rect r(4,5);
Tri t(4,5);
shape=&r;
shape->area();
shape=&t;
shape->area();
return 0;
}
显示你的代码。 –
与其依靠人们阅读链接的文章(当数年后有人发现此问题时可能不存在),请将相关代码示例作为问题的一部分发布,以便我们可以自行理解它。堆栈溢出不仅仅是为了你现在需要的答案,而是其他人未来的相同问题。 –
道歉。在上面的第一个问题中添加了代码。谢谢 – Gangadhar