2013-03-03 36 views
1

我在我的代码如下声明含义:变化从类型定义

typedef QString       String; 

然后在另一头我做的:

class MyClass { 
    typedef String String; 
}; 

,并出现以下错误:

error: changes meaning of 'String' from 'typedef class QString String' [-fpermissive] 

使用这个重新声明有什么错误?

回答

2

由于有这种类型别名的工作方式,它看起来你的编译器就像你试图定义MyClass::String内的本身。它变得困惑。

[C++11: 7.1.3/6]: In a given scope, a typedef specifier shall not be used to redefine the name of any type declared in that scope to refer to a different type. [..]

这里有一个完整的例子:

typedef int alias_t; 

class T 
{ 
    typedef alias_t alias_t; 
}; 

Output

test.cpp:4: error: declaration of 'typedef alias_t T::alias_t'
test.cpp:1: error: changes meaning of 'alias_t' from 'typedef int alias_t'


我可以fix this example通过添加::前缀现有类型:

typedef int alias_t; 

class T 
{ 
    typedef ::alias_t alias_t; 
}; 

在你的代码,即转化为以下几点:

class MyClass 
{ 
    typedef ::String String; 
}; 
+0

我记得有关性病规则确保一个名称在类范围只是一个单一的含义。 – 2013-03-03 21:49:49

+0

只是想知道;如果'MyClass'在某个'namespace myNameSpace'中,会不会破坏? – bitmask 2013-03-03 21:50:15

+0

@bitmask定义 “是”。 – 2013-03-03 21:52:31