C++ 类中的结构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8550711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:47:06  来源:igfitidea点击:

struct in class

c++classstruct

提问by Wizard

I have struct in class and not know how to call variables from struct, please help ;)

我在课堂上有结构体,但不知道如何从结构体中调用变量,请帮忙;)

#include <iostream>
using namespace std;

class E
{
public: 
    struct X
    {
        int v;
    };
};

int main(){

E object;
object.v=10; //not work 

return 0;
}

回答by Filip Roséen - refp

I declared class B inside class A, how do I access it?

我在 A 类中声明了 B 类,如何访问它?

Just because you declare your struct Binside class Adoes not mean that an instance of class Aautomatically has the properties of struct Bas members, nor does it mean that it automatically has an instance of struct Bas a member.

仅仅因为你声明了你的struct Binside class A,并不意味着实例class A自动具有struct B成员属性,也不意味着它的实例自动具有struct B成员成员。

There is no true relation between the two classes (Aand B), besides scoping.

除了作用域之外,两个类(AB)之间没有真正的关系。



struct A { 
  struct B { 
    int v;
  };  

  B inner_object;
};

int
main (int argc, char *argv[]) {
  A object;
    object.inner_object.v = 123;
}

回答by Johnsyweb

It's not clear what you're actually trying to achieve, but here are two alternatives:

目前尚不清楚您实际想要实现的目标,但这里有两种选择:

class E
{
public:
    struct X
    {
        int v;
    };

    // 1. (a) Instantiate an 'X' within 'E':
    X x;
};

int main()
{
    // 1. (b) Modify the 'x' within an 'E':
    E e;
    e.x.v = 9;

    // 2. Instantiate an 'X' outside 'E':
    E::X x;
    x.v = 10;
}

回答by geniaz1

You should define the struct out of the class like this:

您应该像这样在类之外定义结构:

#include <iostream>
using namespace std;
struct X
{
        int v;
};
class E
{
public: 
      X var;
};

int main(){

E object;
object.var.v=10; 

return 0;
}

回答by Mat

Your Eclass doesn't have a member of type struct X, you've just defined a nested struct Xin there (i.e. you've defined a new type).

您的E类没有 type 成员struct X,您只是struct X在其中定义了一个嵌套(即您定义了一个新类型)。

Try:

尝试:

#include <iostream>

class E
{
    public: 
    struct X { int v; };
    X x; // an instance of `struct X`
};

int main(){

    E object;
    object.x.v = 1;

    return 0;
}

回答by Mat

If you give the struct no name it will work

如果你给结构没有名字,它会起作用

class E
{
public: 
    struct
    {
        int v;
    };
};

Otherwise write X x and write e.x.v

否则写 X x 和写 exv