私有结构(在类中定义)是否可以不用作属于同一类的函数的返回类型?

时间:2015-04-08 07:18:34

标签: c++

我正在研究BST。相关代码如下: - 这是类定义: -

class BST
{

private:
    struct Leaf
    {
      int val;
      int count;
      Leaf *left,*right;
    };


Leaf *root;  // This is unique for entire class;

public:
   BST()    // Constructor for BST
    {
      root = NULL;
    }

    void Insert(); // Insert in the BST
    Leaf* InsertNode(Leaf *pos,Leaf *node);  // Recursive and Consize function to Insert the node,extention of Insert func
    void Search(); // Search in the BST
    bool SearchNode(Leaf *pos,int val); // Recursive and Consize function to Search the node,extention of Search func
    int Count(Leaf *Node);  // Count the children of a Node
    void Print();  // Print the BST
    void Inorder(Leaf *Node,int indent);
    void Delete(); // Delete a node in BST
    Leaf* DeleteNode(Leaf *pos,int val);  // Recursive and Consize function to Delete the node,extention of Delete func


};

这是插入函数的定义: -

Leaf* BST::InsertNode(Leaf *pos,Leaf *node)
{
    if(pos == NULL)
    {
      return node;
    }
    if(pos->val > node->val)
        pos->left = InsertNode(pos->left,node);
    if(pos->val < node->val)
        pos->right = InsertNode(pos->right,node);   

    return pos;
}

我收到编译错误: -

bst.cpp(81): error C2143: syntax error : missing ';' before '*'
bst.cpp(81): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
bst.cpp(82): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
bst.cpp(82): error C2556: 'int *BST::InsertNode(BST::Leaf *,BST::Leaf *)' : overloaded function differs only by return type from 'BST::Leaf *BST::InsertNode(BST::Leaf *,BST::Leaf *)'

即使我公开了Structure结构,该错误仍然存​​在。 只有当我在类外面声明结构时,错误才会消失。

有人可以解释一下这背后的原因是什么?

1 个答案:

答案 0 :(得分:1)

问题不是访问控制,而是范围界定。 Leaf中定义了BST,因此其名称位于BST范围内:

BST::Leaf* BST::InsertNode(BST::Leaf *pos, BST::Leaf *node)

现在,作为BST的私有类型会对非朋友如何访问该类型设置一些限制。他们无法说出

BST::Leaf* leaf = foo.InsertNode(bar, baz);

但他们可以说

auto leaf = foo.InsertNode(bar, baz);

从表面上看,BST::Leaf应为public