gpt4 book ai didi

C++继承与方法重载混淆

转载 作者:太空狗 更新时间:2023-10-29 20:44:24 30 4
gpt4 key购买 nike

对不起,这太做作了,但它涉及到作业问题。我明白为什么一切都会发生,除了我评论的那一行。有人可以向我解释为什么 C++ 正在做它正在做的事情吗?

谢谢

#include <iostream>

using namespace std;

class X0 {};
class X1: public X0 {};
class X2: public X1 {};

class Y1
{
public:
virtual void f(int v) { cout << "Y1(int)" << endl; }
virtual void f(const X0 *x) { cout << "Y1(X0)" << endl; }
virtual void f(const X1 *x) { cout << "Y1(X1)" << endl; }
};

class Y2: public Y1
{
public:
virtual void f(const X0 *x) { cout << "Y2(X0)" << endl; }
virtual void f(const X1 *x) { cout << "Y2(X1)" << endl; }
virtual void f(const X2 *x) { cout << "Y2(X2)" << endl; }
};

int main(int argc, char * argv[])
{
X2 x2; X2 *X2Pointer = &x2;
Y2 y2; Y1 *Y1Pointer = &y2;

cout << "What is about to happen?" << endl;
//Y1 pointer points to a Y2 object.
//The Y2 class, upon being given an X2 pointer, should print Y2(X2)
Y1Pointer->f(X2Pointer);
cout << "Why did I just print Y2(X1)" << endl;
return 0;
}

最佳答案

Y1 类公开了这些 f() 的重载:

class Y1: public Y0 {
public:
virtual void f(int v) { cout << "Y1(int)" << endl; }
virtual void f(const X0 *x) { cout << "Y1(X0)" << endl; }
virtual void f(const X1 *x) { cout << "Y1(X1)" << endl; }
// ...
};

所有其他从 Y0 继承的名为 f() 的方法都被隐藏了。也就是说,当你调用

Y1Pointer->f(X2Pointer);

编译器对 f() 的三个重载进行重载解析,得出 f(const X1*) 最匹配的结论,并调用该函数.事实证明,这是一个 virtual 函数,被 Y2 覆盖,因此调用 Y2::f(const X1*) .

关于C++继承与方法重载混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13332258/

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