繁体   English   中英

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

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

我已经编写了此类以及成员函数,并在main函数中创建了对象。 它调用show函数很好,但是show函数本身说它不能访问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
}

看起来您实际上并未将struct Node的实例定义为bst类的成员。 您定义了嵌套类,但未声明其实例。 声明一个,然后可以使用其下声明的名称来使它起作用,例如:

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
}

您可能希望让root成为bst的成员,在这种情况下,您需要重新安排将其放入bst ,而不是Node类的声明:

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

            void show();
};

在这种情况下,您将不需要使用node.限定引用node. 如第一个示例所示。

暂无
暂无

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

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