gpt4 book ai didi

c++ - 访问基类函数

转载 作者:可可西里 更新时间:2023-11-01 15:23:48 26 4
gpt4 key购买 nike

class Base
{
public: void foo(){}
};

class Derived : public Base
{
private:
using Base::foo;
};

int main()
{
Derived d;
d.foo();
}

代码是否合法? using Base::foo 声明位于派生类的私有(private)部分。所以调用 d.foo() 不应该编译,对吗?

最佳答案

没错。

现在检查现实......

MinGW g++ 4.4.1:

x.cpp: In function 'int main()': x.cpp:3: error: 'void Base::foo()' is inaccessible
x.cpp:15: error: within this context

Visual C++ 10.0:

x.cpp(15) : error C2248: 'Derived::foo' : cannot access private member declared in class 'Derived'
x.cpp(9) : see declaration of 'Derived::foo'
x.cpp(6) : see declaration of 'Derived'

Comeau Online 4.3.10.1:

In strict mode, with -tused, Compile succeeded (but remember, the Comeau online compiler does not link).
Compiled with C++0x extensions enabled.

糟糕。 Comeau 几乎总是正确的!好吧,为 C++98/C++03 关闭 C++0x 扩展:

In strict mode, with -tused, Compile succeeded (but remember, the Comeau online compiler does not link).
Compiled with C++0x extensions DISabled.

糟糕!

好吧,正如他们在挪威所说的那样(字面翻译成英文),you biggie mine。

我会尝试将此事报告给 Comeau。

编辑:既然 Prasoon 也回答了,引用了神圣标准,他对此的解释与我上面写的相矛盾,好吧,standadeese……

§11.3/1 “可以在派生类中更改基类成员的访问权限……”,等等,尽可能清楚(无需解释)。并举一个具体的例子。以及说明这等同于 using 声明的规范文本。

干杯,

关于c++ - 访问基类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4305597/

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