gpt4 book ai didi

c++ - 名称隐藏和访问基类的非虚函数(语法)

转载 作者:行者123 更新时间:2023-11-28 07:38:29 25 4
gpt4 key购买 nike

在下面的代码中:

#include <iostream>

class A
{
public:
void f( float x ) { std::cout << 1; }
void g() { std::cout << 11; }
};

class B : public A
{
public:
void f( char x ) { std::cout << 2; }
void g() { std::cout << 22; }
};

int main()
{
B b;
b.A::f( 0 );
b.A::g();

return 0;
}

这名字不是藏起来了吗? 标准(C++11 或 C++03,无所谓,这两个标准似乎都一样)中定义的语法在哪里?

我根本不知道这是可能的,那是我第一次看到这样的语法(第一次在这里看到:why cant i access class A function in following code?)

最佳答案

是的,它是名字隐藏。因此它不会重载(也不会覆盖)。 N3485 中的 13.2 声明匹配 部分解释了这一点。

13.2 Declaration matching

1 Two function declarations of the same name refer to the same function if they are in
the same scope and have equivalent parameter declarations (13.1). A function member of
a derived class is not in the same scope as a function member of the same name in a base class.

[ Example:


struct B {
int f(int);
};

struct D : B {
int f(const char*);
};
Here D::f(const char*) hides B::f(int) rather than overloading it.
void h(D* pd) {
pd->f(1); // error:
// D::f(const char*) hides B::f(int)
pd->B::f(1); // OK
pd->f("Ben"); // OK, calls D::f
}

--例子结束]

关于c++ - 名称隐藏和访问基类的非虚函数(语法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16295612/

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