2009-05-27 96 views
8

我試圖訪問一個成員結構變量,但我似乎無法得到正確的語法。 這兩個編譯錯誤公關。訪問是: 錯誤C2274:'功能風格強制轉換':非法作爲'。'的右側。運算符 錯誤C2228:'.otherdata'的左邊必須有class/struct/union 我試過了各種更改,但都沒有成功。C++:從類指針訪問成員結構的語法

#include <iostream> 

using std::cout; 

class Foo{ 
public: 
    struct Bar{ 
     int otherdata; 
    }; 
    int somedata; 
}; 

int main(){ 
    Foo foo; 
    foo.Bar.otherdata = 5; 

    cout << foo.Bar.otherdata; 

    return 0; 
} 

回答

15

你只在那裏定義一個結構體,而不是分配一個結構體。試試這個:

class Foo{ 
public: 
    struct Bar{ 
     int otherdata; 
    } mybar; 
    int somedata; 
}; 

int main(){ 
    Foo foo; 
    foo.mybar.otherdata = 5; 

    cout << foo.mybar.otherdata; 

    return 0; 
} 

如果你想重用其他類的結構,也可以外定義的結構:

struct Bar { 
    int otherdata; 
}; 

class Foo { 
public: 
    Bar mybar; 
    int somedata; 
} 
+0

謝謝,完全忘了那個。並且像魅力一樣工作。 – 2009-05-27 11:07:37

+4

代碼不完全相同。在第一個示例中,Bar結構的名稱實際上是Foo :: Bar。 – 2009-05-27 11:09:09

8

Bar裏面Foo定義的內部結構。創建Foo對象不會隱式創建Bar的成員。您需要使用Foo::Bar語法明確創建Bar的對象。

Foo foo; 
Foo::Bar fooBar; 
fooBar.otherdata = 5; 
cout << fooBar.otherdata; 

否則,

Foo類來創建欄實例作爲成員。

class Foo{ 
public: 
    struct Bar{ 
     int otherdata; 
    }; 
    int somedata; 
    Bar myBar; //Now, Foo has Bar's instance as member 

}; 

Foo foo; 
foo.myBar.otherdata = 5; 
5

您創建了一個嵌套結構,但是您從不在類中創建它的任何實例。你需要這樣說:

class Foo{ 
public: 
    struct Bar{ 
     int otherdata; 
    }; 
    Bar bar; 
    int somedata; 
}; 

那麼你可以說:

foo.bar.otherdata = 5; 
1

你只宣佈美孚::酒吧,但(如果這是正確的術語不知道)你不實例化它

看到這裏的用法:

#include <iostream> 

using namespace std; 

class Foo 
{ 
    public: 
    struct Bar 
    { 
     int otherdata; 
    }; 
    Bar bar; 
    int somedata; 
}; 

int main(){ 
    Foo::Bar bar; 
    bar.otherdata = 6; 
    cout << bar.otherdata << endl; 

    Foo foo; 
    //foo.Bar.otherdata = 5; 
    foo.bar.otherdata = 5; 

    //cout << foo.Bar.otherdata; 
    cout << foo.bar.otherdata << endl; 

    return 0; 
} 
0
struct Bar{ 
     int otherdata; 
    }; 

在這裏,您剛剛定義了一個結構,但未創建任何對象。因此,當你說foo.Bar.otherdata = 5;這是編譯器錯誤。創建一個對象的結構像吧像Bar m_bar;然後用Foo.m_bar.otherdata = 5;