无法访问派生类中的基本变量

时间:2012-02-29 04:59:27

标签: c++ inheritance polymorphism

以下编译代码显示结果区域为零。一些宽度和高度变量仍然保持为零,即使我们使用基础构造函数设置它。

#include <iostream> 
using namespace std;

class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      virtual int area()
      {
         cout << "Parent class area :" <<endl;
         return 0;
      }
};
class Rectangle: public Shape{
   public:
      Rectangle( int a=0, int b=0)
      {
          Shape(a, b); 
      }
      int area ()
      { 
          cout << "Rectangle class area :" <<endl;
          return (width * height); 
      }
};
class Triangle: public Shape{
    public:
        Triangle( int a=0, int b=0)
        {
            Shape(a, b); 
        }
        int area ()
        { 
            cout << "Rectangle class area :" <<endl;
            return (width * height / 2); 
        }
};
// Main function for the program
int main( )
{
    Shape *shape;
    Rectangle rec(10,7);
    Triangle  tri(10,5);

    // store the address of Rectangle
    shape = &rec;
    // call rectangle area.
    cout << shape->area() << endl;

   // store the address of Triangle
   shape = &tri;
   // call triangle area.
   cout << shape->area() << endl;

   return 0;
}

输出: 矩形类区域: 0 矩形类区域: 0

试图找出区域为零的原因以及如何让pgm打印实际区域?

2 个答案:

答案 0 :(得分:1)

正确的语法是:

Rectangle( int a=0, int b=0) : Shape(a, b)
{                       //     ^^^^^^^^^^^^
}

您需要将Shape构造函数作为初始化列表的一部分进行调用 如您的示例所示,如果您将其写为语句

{
  Shape(a,b);  // <--- no effect on Base part
}

然后,创建并销毁临时Shape对象,因此它没有任何效果。

答案 1 :(得分:0)

你的子类的构造函数应该如下,

 Rectangle( int a=0, int b=0)
      :Shape(a, b) //call base class constructor
  {
      //Shape(a, b); // you are creating new object of shape here , not calling base constructor 
  }
相关问题