试图通过指针访问嵌套类的成员函数 我对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;