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

Pet*_*ted 8 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;
}
Run Code Online (Sandbox Code Playgroud)

sch*_*der 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;
}
Run Code Online (Sandbox Code Playgroud)

如果要在其他类中重用结构,还可以在外部定义结构:

struct Bar {
  int otherdata;
};

class Foo {
public:
    Bar mybar;
    int somedata;
}
Run Code Online (Sandbox Code Playgroud)

  • 代码并不完全等效.在第一个示例中,Bar结构的名称实际上是Foo :: Bar. (4认同)

aJ.*_*aJ. 8

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

Foo foo;
Foo::Bar fooBar;
fooBar.otherdata = 5;
cout << fooBar.otherdata;
Run Code Online (Sandbox Code Playgroud)

除此以外,

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;
Run Code Online (Sandbox Code Playgroud)


小智 5

您创建了一个嵌套结构,但您从未在类中创建它的任何实例.你需要说:

class Foo{
public:
    struct Bar{
        int otherdata;
    };
    Bar bar;
    int somedata;
};
Run Code Online (Sandbox Code Playgroud)

然后你可以说:

foo.bar.otherdata = 5;
Run Code Online (Sandbox Code Playgroud)