【问题标题】:C++: syntax for accessing member struct from pointer to classC++:从指向类的指针访问成员结构的语法
【发布时间】:2023-03-09 15:13:01
【问题描述】:

我正在尝试访问成员结构变量,但我似乎无法正确使用语法。 这两个编译错误pr。访问是: 错误 C2274:“函数样式转换”:作为“。”的右侧是非法的操作员 错误 C2228:“.otherdata”左侧必须有类/结构/联合 我尝试了各种更改,但都没有成功。

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

【问题讨论】:

    标签: c++ struct member


    【解决方案1】:

    你只在那里定义一个结构,而不是分配一个。试试这个:

    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:

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

    【讨论】:

    • 代码并不完全等价。在第一个示例中,Bar 结构的名称实际上是 Foo::Bar。
    【解决方案2】:

    Bar 是在Foo 内部定义的内部结构。 Foo 对象的创建不会隐式创建Bar 的成员。您需要使用Foo::Bar 语法显式创建 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;
    

    【讨论】:

    • 比起传统的C风格“struct { } ”,我更喜欢这种风格。
    【解决方案3】:

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

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

    然后你可以说:

    foo.bar.otherdata = 5;
    

    【讨论】:

      【解决方案4】:

      您只是在声明 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;
      }
      

      【讨论】:

        【解决方案5】:
        struct Bar{
                int otherdata;
            };
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-04
          • 1970-01-01
          • 2022-11-01
          • 1970-01-01
          • 2023-03-12
          • 1970-01-01
          • 2018-03-24
          • 1970-01-01
          相关资源
          最近更新 更多