gpt4 book ai didi

c++ - 私有(private)结构(在类中定义)不能用作属于同一类的函数的返回类型吗?

转载 作者:行者123 更新时间:2023-11-30 05:45:05 24 4
gpt4 key购买 nike

我正在研究 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 的声明,错误仍然存​​在。只有当我在类外声明结构时,错误才会消失。

谁能解释一下这背后的原因是什么?

最佳答案

问题不在于访问控制,而在于范围界定。 Leaf定义在BST中,所以它的名字在BST范围内:

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

现在,作为 BST 的私有(private)类型对非好友访问该类型的方式施加了一些限制。他们不能说

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

但他们可以说

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

从表面上看,BST::Leaf 应该是public

关于c++ - 私有(private)结构(在类中定义)不能用作属于同一类的函数的返回类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29508313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com