Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
试图通过指针访问嵌套类的成员函数 我对C++非常陌生,认为这个问题与指针相关。四处调查,但找不到任何与以下上下文相关的明显信息_C++_Class_Pointers_Tree_Member - Fatal编程技术网

试图通过指针访问嵌套类的成员函数 我对C++非常陌生,认为这个问题与指针相关。四处调查,但找不到任何与以下上下文相关的明显信息

试图通过指针访问嵌套类的成员函数 我对C++非常陌生,认为这个问题与指针相关。四处调查,但找不到任何与以下上下文相关的明显信息,c++,class,pointers,tree,member,C++,Class,Pointers,Tree,Member,我概述了我的代码结构,以突出我遇到的问题,即试图通过指向常量节点的指针root,访问嵌套的节点类成员函数isLeftChild;我可以使isLeftChild成为树类的成员函数,但觉得isLeftChild成为嵌套的节点类的成员函数更符合逻辑 class Tree { class Node { public: bool isLeftChild(void); }; Node const* root; public:

我概述了我的代码结构,以突出我遇到的问题,即试图通过指向常量
节点的指针
root
,访问嵌套的
节点
类成员函数
isLeftChild
;我可以使
isLeftChild
成为
类的成员函数,但觉得
isLeftChild
成为嵌套的
节点
类的成员函数更符合逻辑

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;
    }
}
类树{
类节点{
公众:
布尔伊斯莱夫奇尔德(无效);
};
节点常数*根;
公众:
无效遍历(节点常数*根);
};
无效树::遍历(节点常量*根){
//***下一行给出了编译错误:请求中的成员“isLeftChild”
//“root”,属于非类类型“const Tree::Node*”
if(root.isLeftChild()){
cout parent!=NULL;
if(hasParent){
返回this==this->parent->left;
}否则{
返回false;
}
}
如何从
遍历
成员函数中访问此成员函数?问题是否围绕
是指针这一事实

谢谢你,亚历克斯

谢谢你:

root.isLeftChild()
为此:

root->isLeftChild()
操作员
将对对象进行操作

操作符
->
将作用于指向对象的指针。如
root


这就是为什么错误告诉您
root
是非类类型。它是指针类型。

因为您有一个指向const参数的指针,所以只能对其调用const方法

试一试


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

Hi@DrewDormann修改为
root->isLeftChild()
,但出现编译错误:将'const Tree::Node'作为'bool Tree::Node::isLeftChild()的'this'参数传递'丢弃限定符我已将
isLeftChild
定义的内容添加到上面的代码中,以防这里出现其他问题。谢谢@molbdnilo在看到您的答案之前刚刚尝试添加
const
;正在尝试
bool const isLeftChild()
但我假设在
isLeftChild()之后设置
const
将方法设置为
const
方法,而不是将返回类型
bool
设置为
const
 bool isLeftChild() const;