c++ - 为什么 C++11 中仍然需要 "using"指令来从基类中引入在派生类中重载的方法

标签 c++ gcc c++11 overloading using-directives

下面的示例得到以下编译错误:

test.cpp: In function ‘int main(int, char**)’:
test.cpp:26:8: error: no match for call to ‘(Derived) (p1&)’
test.cpp:14:8: note: candidate is:
test.cpp:16:10: note: void Derived::operator()(const p2&)
test.cpp:16:10: note:   no known conversion for argument 1 from ‘p1’ to ‘const p2&’

据我所知,这在 C++11 中有所改变,因此您不需要将 using 语句放入其中。这不正确吗?还有其他解决方法吗?

示例(使用 --std=c++11 使用 gcc 4.7 编译):

#include <iostream>
#include <string>

using namespace std;

struct p1{};
struct p2{};

struct Base
{
    void operator()(const p1&) { cout << "p1" << endl; }
};

struct Derived : public Base
{
    void operator()(const p2&) { cout << "p2" << endl; }
    //Works if I include: using Base::operator();
};

int main(int argc, char** argv)
{
    p1 p;
    p2 pp;
    Derived d;

    d(p);
    d(pp);
}

最佳答案

据我所知,不,这在 C++11 中没有改变。

而它没有改变的原因是这种行为不是偶然的。该语言的设计就是这样工作的。它有利也有弊,但这并不是因为标准委员会的人忘记了它而发生的事情。

不,没有办法绕过它。这就是成员查找在 C++ 中的工作方式

关于c++ - 为什么 C++11 中仍然需要 "using"指令来从基类中引入在派生类中重载的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11461270/

相关文章:

c++ - 在C++中定义工厂类

C++ 嵌套 pragma 警告推送/弹出

c++ - 通过套接字进行数据传输[TCP]如何在c/c++中打包多个整数并使用send()recv()传输数据?

windows - Cygwin 64 位 C 编译器缓存有趣(并且提前结束)

c++ - Qt 5.7.1/GCC 6.3.0:错误:constexpr函数的主体'静态constexpr int QMetaTypeId2 <T>

c++ - 句柄而不是指针的引用计数

c++ - 符号可见性和 gcc 警告

c - 如何防止包含 C 库析构函数和 atexit()?

c++ - C++ 编译器隐式实例化模板类的所有成员函数是否有效?

c++ - 静态指针对函数的 undefined reference