【发布时间】:2015-12-02 06:43:15
【问题描述】:
我创建了一个需要帮助的场景。下面的代码是相同的示例测试应用程序。
#include <iostream>
using namespace std;
class A
{
public:
typedef int mytype;
mytype GetInt() { return 1;}
};
class B
{
public:
typedef char mytype;
};
class C : public A, public B
{
};
class D : public C
{
public:
void scenario()
{
mytype m = GetInt();
}
};
int main()
{
D d1;
d1.scenario();
return 0;
}
编译代码使用:g++ tmp.cpp
Error:
tmp.cpp:27:9: error: reference to ‘mytype’ is ambiguous
mytype m = GetInt();
^
tmp.cpp:15:18: note: candidates are: typedef char B::mytype
typedef char mytype;
^
tmp.cpp:8:17: note: typedef int A::mytype
typedef int mytype;
^
tmp.cpp:27:16: error: expected ‘;’ before ‘m’
mytype m = GetInt();
从代码中我们可以看出,GetInt() 仅在 A 类中定义,因此我认为 mytype 将仅从 A 类中获取。但根据错误日志,情况并非如此。
我们可以通过添加类A的范围来解决这个问题
A::mytype m = GetInt();
我想知道: 在这种情况下编译器的行为如何? 是否有 ant 编译器标志可以在 gcc 的情况下解决此错误?
【问题讨论】:
-
您也可以使用
auto的类型推导,如auto m = GetInt();(如果您有处理 C++11 或更高版本的编译器)。 -
@JoachimPileborg 感谢您提供解决此问题的另一种方法。
标签: c++ typedef multiple-inheritance ambiguity name-lookup