2013-03-03 99 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