我正在研究一个解析器来构建抽象语法树.
我的所有节点都有这个Node基类.
// Base for all nodes
class Node {
public:
virtual ~Node();
virtual int position() = 0; // code string index of first character associated with this Node
virtual int end() = 0; // code string index of first immediately after the last character associated with this Node
};
Run Code Online (Sandbox Code Playgroud)
其中一个子类是表达式节点:
// Expression node
class ExpressionNode: Node {
public:
virtual ~ExpressionNode();
virtual int position() = 0;
virtual int end() = 0;
};
Run Code Online (Sandbox Code Playgroud)
其中一个子类是一个标识符节点,我在其中一个成员上遇到一个非常奇怪的错误:
// Identifier Expression
class IdentNode: ExpressionNode {
public:
int namePosition;
std::string name;
Node *n; // Error - 'Node' is a private member of 'Node'
IdentNode();
~IdentNode();
virtual int position();
virtual int end();
};
Run Code Online (Sandbox Code Playgroud)
为什么我会收到此错误?老实说,我很困惑.
(我假设您希望ExpressionNode从Node派生.)默认情况下,继承是private,这意味着派生类无法访问基类成员.使用protected(成员可以通过派生而不是其他范围访问)或public继承(基础中的所有公共成员都可以在任何地方访问).
class ExpressionNode : public Node {
...
class IdentNode : public ExpressionNode {
Run Code Online (Sandbox Code Playgroud)