C ++:从指针到类访问成员结构的语法

时间:2009-05-27 10:53:22

标签: c++ struct member

我正在尝试访问成员结构变量,但我似乎无法正确使用语法。 两个编译错误pr。访问是: 错误C2274:'function-style cast':非法作为'。'的右侧。操作者 错误C2228:'。altdata'的左边必须有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;
}

5 个答案:

答案 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;
}

答案 1 :(得分:8)

BarFoo内定义的内部结构。创建Foo对象不会隐式创建Bar的成员。您需要使用Foo::Bar语法显式创建Bar的对象。

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

否则,

Foo类中创建Bar实例作为成员。

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;

答案 2 :(得分:5)

您创建了一个嵌套结构,但是您永远不会在类中创建它的任何实例。你需要说出类似的话:

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

然后你可以说:

foo.bar.otherdata = 5;

答案 3 :(得分: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;
}

答案 4 :(得分:0)

struct Bar{
        int otherdata;
    };

在这里,您刚刚定义了一个结构,但没有创建任何对象。因此,当你说foo.Bar.otherdata = 5;时,编译错误。创建一个struct Bar的对象,如Bar m_bar;,然后使用Foo.m_bar.otherdata = 5;