【问题标题】:Trying to access member function of nested class through pointer试图通过指针访问嵌套类的成员函数
【发布时间】:2013-03-31 16:38:36
【问题描述】:

我对 C++ 很陌生,并且认为这个问题从根本上与指针有关;进行了研究,但找不到与以下上下文相关的任何明显内容。

我已经概述了我的代码结构,以突出我遇到的问题,它试图通过指针root 访问嵌套的Node 类成员函数isLeftChild 到常量Node;我可以让isLeftChild 成为Tree 类的成员函数,但我觉得isLeftChild 成为嵌套Node 类的成员函数更合乎逻辑。

class Tree {

    class Node {
        public:
            bool isLeftChild(void);
    };

    Node const* root;
    public:
        void traverse(Node const* root);
};

void Tree::traverse(Node const* root) {
    // *** Line below gives compile error: request for member 'isLeftChild' in 
    //     'root', which is of non-class type 'const Tree::Node*'
    if ( root.isLeftChild() ) {
        cout << "[is left child]";
    }
}

bool Tree::Node::isLeftChild(void){
    bool hasParent = this->parent != NULL;

    if ( hasParent ) {
        return this == this->parent->left;
    } else {
        return false;
    }
}

如何从traverse 成员函数中访问此成员函数?问题是否围绕root 是一个指针这一事实?

谢谢,亚历克斯

【问题讨论】:

    标签: c++ class pointers tree member


    【解决方案1】:

    因为你有一个指向 const 参数的指针,你只能在它上面调用 const 方法。

    试试

     bool isLeftChild() const;
    

    并将“const”也添加到实现中。

    【讨论】:

    • 谢谢@molbdnilo 只是想在我看到你的答案之前添加const;正在尝试bool const isLeftChild(),但我认为在isLeftChild() 之后设置const 将方法设置为const 方法,而不是将返回类型bool 设置为const
    【解决方案2】:

    改变这个:

    root.isLeftChild()
    

    到这里:

    root->isLeftChild()
    

    运算符. 将作用于一个对象

    运算符-&gt; 将作用于指向对象的指针。喜欢root

    这就是错误告诉您root 是非类类型的原因。是指针类型。

    【讨论】:

    • 嗨 @DrewDormann 修改为 root-&gt;isLeftChild() 但得到编译错误:将 'const Tree::Node' 作为 'bool Tree::Node::isLeftChild()' 的 'this' 参数传递丢弃限定符 我已将isLeftChild 定义的内容添加到我上面的代码中,以防这里可能存在其他问题。
    猜你喜欢
    • 2020-02-06
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多