gpt4 book ai didi

C++:涉及继承和 "using"时的方法重载

转载 作者:行者123 更新时间:2023-11-30 01:39:32 25 4
gpt4 key购买 nike

假设有两个类:Base 类和 Derived 类。代码如下所示。 我的问题是,程序如何知道d.print()(在代码中用A标记)意味着调用Derived::print() 而不是 Base::print()

请注意,我故意添加了 using Base::print; 来迷惑编译器。这两个 print() 方法具有相同的签名(我说得对吗?),并且不会因为 using 语句而相互隐藏。

#include <iostream>
using namespace std;

class Base {
public:
void print() { cout << "print() of Base is called\n"; }
};

class Derived : public Base {
public:
void print() { cout << "print() of Derived is called\n"; }
using Base::print; // I delibarately added this line
};

int main() {
Derived d;
d.print(); // A

Base *pBase = (Base *)&d;
pBase->print(); // B
}

结果是

 print() of Derived is called
print() of Base is called

编辑:接受的答案给出了报价。为了方便读者,我将(几乎)整个引用的段落粘贴在这里,分成句子:

Using-declaration introduces a member of a base class into the derived class definition, such as to expose a protected member of base as public member of derived.. (that's what I expected)

If the name is the name of an overloaded member function of the base class, all base class member functions with that name are introduced. (that's what I expected, too)

If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class. (solved my problem)

最佳答案

由于此规则(来自 cppreference documentation for using),显式引入的 using 不会隐藏派生类中的方法

If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class.

编译器并没有感到困惑,它正在做正确的事情。 using 并未隐藏派生类中的 print() 方法,因为它定义了 print() 方法。

当您使用Base指针调用print()时,print()不是虚拟的,基指针只能调用该方法已注册为其所指向事物的静态类型,即 Base::print()

关于C++:涉及继承和 "using"时的方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45476670/

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