9

メンバー構造体変数にアクセスしようとしていますが、正しい構文を取得できないようです。2 つのコンパイル エラー pr。アクセスは次のとおりです: エラー C2274: '関数スタイルのキャスト': '.' の右側として不正です operator error C2228: '.otherdata' の左側には class/struct/union が必要です さまざまな変更を試みましたが、成功しませんでした。

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

5 に答える 5

17

そこに構造体を定義するだけで、割り当てはしません。これを試して:

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;
}
于 2009-05-27T10:56:52.800 に答える
9

Bar内部構造は内部で定義されていFooます。object の作成は、のメンバーFooを暗黙的に作成しません。構文Barを使用して Bar のオブジェクトを明示的に作成する必要があります。Foo::Bar

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

さもないと、

Bar インスタンスを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;
于 2009-05-27T10:57:41.393 に答える
5

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

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

次に、次のように言うことができます。

foo.bar.otherdata = 5;
于 2009-05-27T10:58:05.217 に答える
1

Foo::Bar を宣言しているだけですが、インスタンス化していません (それが正しい用語かどうかはわかりません)。

使い方はこちらをご覧ください:

#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;
}
于 2009-05-27T11:00:11.437 に答える
0
struct Bar{
        int otherdata;
    };

ここでは、構造を定義しましたが、そのオブジェクトは作成していません。foo.Bar.otherdata = 5;したがって、それがコンパイラエラーであると言うとき。struct Bar のようなオブジェクトを作成してBar m_bar;から使用しますFoo.m_bar.otherdata = 5;

于 2009-05-27T11:00:20.610 に答える