2013-11-01 124 views
0

下面的代碼無法使用Visual Studio與2012錯誤編譯:C2234:「富」:引用數組是非法索引屬性如何返回引用?

struct MyClass 
{ 
    int m_var; 
    __declspec(property(get=GetFoo)) int& Foo[]; // < C2234 
    int& GetFoo(int) { return m_var; } 
}; 

我不知道爲什麼是這種情況。

是的,引用數組是被標準禁止的。 但是,Foo []不是一個數組,而是一種到成員函數GetFoo()的符號鏈接。 它的行爲就像Foo是一個帶有重載索引操作符的類。 另一方面,下面的代碼是完全合法的,雖然它是在技術上相當於以前的片段:

struct FooClass 
{ 
    int m_var; 
    int& operator[](int) { return m_var; } 
}; 

struct MyClass 
{ 
    FooClass Foo; 
}; 

那麼,爲什麼錯誤C2234發出?這是一個編譯器設計錯誤?

順便說一句:真實的場景更復雜,所以沒有必要告訴我,交給成員的引用可能是一個壞主意。

回答

2

我對此錯誤並不感到驚訝,因爲int& Foo[];是int引用數組的聲明。 __declspec(property)的語法規定該關鍵字後面的內容是一個聲明符:__declspec(property) documentation。因此,您應該將__declspec(property)右側的文字作爲聲明來對待,而不是將其視爲特定的符號鏈接。

正如你和你的編譯器指出的那樣,聲明引用數組是被禁止的。 __declspec(property)也不會違反該規則。

您可以使用此替代:

struct MyClass 
{ 
    int m_var; 
    __declspec(property(get=GetFoo,put=SetFoo)) int Foo[]; // < C2234 
    int& GetFoo(int) { return m_var; } 
    void SetFoo(int, int v) {m_var = v;} 
}; 

int main() 
{ 
    MyClass test; 
    test.Foo[0] = 5; 

    std::cout << test.Foo[0]; 

    return 0; 
} 

如果我是你,我會堅持到好醇」運算符[],這是標準的C++。 __declspec語法特定於Microsoft的Visual Studio。