gpt4 book ai didi

c++ - 为什么 C++ 不支持跨作用域重载?

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

我相信这里已经给出了最佳答案:Why does an overridden function in the derived class hide other overloads of the base class?

但我有点困惑,特别是声明:

In order to override this behavior, an explicit action is required from the user: originally a redeclaration of inherited method(s) (currently deprecated), now an explicit use of using-declaration.

假设我有以下程序:

#include <iostream>
using namespace std;
class Base
{
public:
int f(int i)
{
cout << "f(int): ";
return i+3;
}
};
class Derived : public Base
{
public:
double f(double d)
{
cout << "f(double): ";
return d+3.3;
}
};
int main()
{
Derived* dp = new Derived;
cout << dp->f(3) << '\n';
cout << dp->f(3.3) << '\n';
delete dp;
return 0;
}

我有两个问题:

  1. 我可以假设,对于派生类对象,int f(int i) 函数根本不存在。这不是因为名字隐藏而继承的。

  2. 如果我必须在派生类中使用这个函数,我必须在派生类中重新定义它吗?

最佳答案

  1. Can I assume, w.r.t derived class object, the int f(int i) function does not exist at all. This is not inherited because of name hiding.

继承的,它只是...隐藏,如果不指定范围(unqualified name lookup)是找不到的。你可以指定它显式地使用范围解析运算符 :: ( qualified name lookup ) :

dp->Base::f(3);
  1. If I have to use this function in Derived class, I have to define it again in derived class?

正如引用的答案所说,您可以通过“明确使用 using-declaration”来实现。

class Derived : public Base
{
public:
using Base::f;
...
};

编辑(来自评论的补充问题)

  1. If it's name hidden, that means I can declare it again ? Same name, same parameters?

是的,你可以。它仍然是名字隐藏。

  1. If yes, what if I also added using Base::f along with the new declaration? Will it result in double definition?

不,这不是双重定义。 Using declaration只是将名称引入派生类范围。而在派生类中声明的成员函数会隐藏从基类中引入的成员函数,仍然是名称隐藏。 (请注意,您仍然可以通过 dp->Base::f(3); 调用基类之一。)

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.

关于c++ - 为什么 C++ 不支持跨作用域重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37861389/

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