2009-05-27 17 views
8

メンバー構造変数にアクセスしようとしていますが、構文を正しく取得できません。 2つのコンパイルエラーが発生しました。アクセスは次のとおりです。 エラーC2274: 'function-style cast': '。'の右側には不正です。演算子 エラーC2228: '.otherdata'の左にはクラス/構造体/共用体が必要です 私はさまざまな変更を試みましたが、成功しませんでした。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

を使用してくださいありがとう、完全に忘れてしまった。そして、魅力のように働く。 –

+4

コードは正確には等価ではありません。最初の例では、Bar構造体の名前は実際はFoo :: Barです。 –

+0

あなたは正しいです、Neil、私の答えを編集しました。 – schnaader

8

BarFoo内で定義された内部構造です。 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; 
+0

私はこのスタイルが伝統的なCスタイルの "struct {} "よりも好きです。 –

5

ネストされた構造を作成しますが、そのクラス内にインスタンスを作成することはありません。あなたはその後、言うことができ

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

foo.bar.otherdata = 5; 
1

あなただけのバー:: Fooのを宣言しているが、(それは正しい用語かどうかわからない)あなたはそれをインスタンス化していないあなたのような何かを言う必要があります

使用方法についてはこちらをご覧ください:

#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;

関連する問題