C ++:从指针到类访问成员struct的语法 [英] C++: syntax for accessing member struct from pointer to class

查看:167
本文介绍了C ++:从指针到类访问成员struct的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图访问一个成员structs变量,但我似乎无法得到正确的语法。
两个编译错误。访问是:
错误C2274:'function-style cast':非法作为'。'的右边
错误C2228:.otherdata的左边必须有类/ struct / union
我尝试了各种更改,但没有成功。

I'm trying to access a member structs variables, but I can't seem to get the syntax right. The two compile errors pr. access are: error C2274: 'function-style cast' : illegal as right side of '.' operator error C2228: left of '.otherdata' must have class/struct/union I have tried various changes, but none successful.

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


推荐答案

,不分配一个。尝试这样:

You only define a struct there, not allocate one. Try this:

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, struct outside:

If you want to reuse the struct in other classes, you can also define the struct outside:

struct Bar {
  int otherdata;
};

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

这篇关于C ++:从指针到类访问成员struct的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆