类指针的调用方法

类指针的调用方法

本文介绍了类指针的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是我有问题,但我发现奇怪的事实。

  / *类形状* / 
class Shape
{
protected:
int width,height;
public:
Shape(int a = 0,int b = 0)
{
width = a;
height = b;
}
int area()
{
cout< Parent class area:<< endl;
return 0;
}
};


/ *类三角形* /
类三角形:public Shape
{
public:
Triangle(int a = 0,int b = 0)
{
Shape(a,b);
}
int area()
{
cout< Triangle class area:<< endl;
return(width * height / 2);
}
};

int main()
{
Shape * shape;
三角形(10,7);


shape =& tri;
(* shape).area();



return 0;
}

上面将打印的是父类区域: p>

所以看来编译器不检查指针内容?和调用方法只基于指针类型?否则,将会看到 * shape 是一个三角形对象,并且将称为区域的三角形版本不是它?



ps。我知道你可以使用虚拟函数,使其工作方式我描述,但现在我感兴趣的,只是我发现这个行为有点怪异,也许我错过了一些东西。

b

  int main()
{
三角形(10,7);
tri.Shape :: area();
}

class Triangle 使用名称 int area()(一个在基础中,一个在派生类中)的两个函数。



int对于 class 的对象,默认情况下将调用三角形:: area() Triangle ,因为它隐藏 int Shape :: area()



通过对指针执行(C风格)强制转换,你告诉你的程序调用类Shape 。因为,正如你所说的,没有虚拟成员函数表(),因为 int Shape :: area()是非,将调用 Shape 版本。



这是预期和明确定义的行为。



示例:







进一步阅读:






Not that I have a problem but I found weird following fact.

/* Class Shape */
class Shape
{
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      int area()
      {
         cout << "Parent class area :" <<endl;
         return 0;
      }
};


/* Class Triangle */
class Triangle: public Shape
{
   public:
      Triangle( int a=0, int b=0)
      {
        Shape(a, b);
      }
      int area ()
      {
         cout << "Triangle class area :" <<endl;
         return (width * height / 2);
      }
};

int main( )
{
   Shape *shape;
   Triangle tri(10,7);


   shape = &tri;
   (*shape).area();



   return 0;
}

What above will be print is: "Parent class area :".

So it seems the compiler does not check the pointer contents? And calls method only based on pointer type? Otherwise it would have seen that *shape is a Triangle object and would have called Triangle version of area isn't it?

ps. I know you can use virtual functions to make it work the way I describe but that't now what I was interested in, just I found this behaviour little bit weird, maybe I am missing something.

解决方案

Your main() function could be simplified to:

int main()
{
    Triangle tri(10,7);
    tri.Shape::area();
}

class Triangle has two functions with the name int area() (one in the base and one in the derived class) .

int Triangle::area() would be called by default for for objects of class Triangle, since it hides int Shape::area().

By performing that (C-style) cast on the pointer, you're telling your program to call the version from class Shape. Since, as you've stated, there is no virtual member function table (vtable) due to int Shape::area() being non-virtual, the Shape version will be called.

This is expected and well-defined behaviour.

Example:

Further reading:

这篇关于类指针的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:03