简体   繁体   English

如何访问类中结构的数据成员?

[英]How would I access the data member of a struct within a class?

I've wrote this class, and the member function, and have created the object in the main function. 我已经编写了此类以及成员函数,并在main函数中创建了对象。 It calls the show function just fine, but the show function itself says that it cannot access root because it is not declared in scope. 它调用show函数很好,但是show函数本身说它不能访问root,因为它没有在作用域中声明。 I set the data members as public, and I didn't think I would need a getter/setter for this. 我将数据成员设置为公共成员,并且我认为不需要此方法。 What's the best way to allow show() access to root? 允许show()访问root的最佳方法是什么?

class bst
{
            public:
            struct Node
            {
                public:
                int data;
                struct Node *left;
                struct Node *right;
                Node* root = NULL;
            };

            void show();

};

void bst::show()
{
    if(root == NULL) return;

    show(root->left);       //Visit left subtree
    printf("%d ",root->data);  //Print data
    show(root->right);      // Visit right subtree
}

It doesn't look like you actually defined an instance of struct Node as a member of your bst class. 看起来您实际上并未将struct Node的实例定义为bst类的成员。 You defined the nested class, but declared no instances of it. 您定义了嵌套类,但未声明其实例。 Declare one, and you can use the name it's declared under to make this work, eg: 声明一个,然后可以使用其下声明的名称来使它起作用,例如:

class bst
{
            public:
            struct Node
            {
                public:
                int data;
                struct Node *left;
                struct Node *right;
                Node* root = NULL;
            };
            Node node;

            void show();
};


void bst::show()
{
    if(node.root == NULL) return;

    show(node.root->left);       //Visit left subtree
    printf("%d ",node.root->data);  //Print data
    show(node.root->right);      // Visit right subtree
}

It's possible you meant for root to be a member of bst , in which case you'd rearrange things to put it in bst , not the declaration of the Node class: 您可能希望让root成为bst的成员,在这种情况下,您需要重新安排将其放入bst ,而不是Node类的声明:

class bst
{
            public:
            struct Node
            {
                public:
                int data;
                struct Node *left;
                struct Node *right;
            };
            Node* root = NULL;

            void show();
};

in which case you wouldn't need to qualify the references with node. 在这种情况下,您将不需要使用node.限定引用node. as shown in the first example. 如第一个示例所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM