gpt4 book ai didi

c++ - 在类指针上调用方法

转载 作者:搜寻专家 更新时间:2023-10-31 01:46:18 24 4
gpt4 key购买 nike

<分区>

不是我有问题,而是我发现事实很奇怪。

/* 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;
}

上面会打印的是:“父类区域:”。

所以编译器似乎没有检查指针内容?并且仅基于指针类型调用方法?否则它会看到 *shape 是一个 Triangle 对象,并且会调用面积的三角形版本,不是吗?

附言。我知道您可以使用虚函数使其按照我描述的方式工作,但这不是我现在感兴趣的,只是我发现这种行为有点奇怪,也许我遗漏了什么。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com