是否可以返回指向类中声明的结构的指针?

时间:2015-04-21 03:08:21

标签: c++ class pointers return

以下代码

class Test{
private:
    struct Node{
        int element;
        Node* next;
    };

    Node* stupidFunction(); // Line 8
};

///////////////////////////////

struct Node;

Node* Test::stupidFunction(){ // Line 15
    Node foo;
    return &foo;
}

///////////////////////////////

int main(){}

将无法编译并提供以下错误消息:

Line 15: error: prototype for 'Node* Test::studpidFunction()' does not match any in class 'Test'
Line 8: error: candidate is: Test::Node* Test::stupidFunction()

是否无法返回指向类中声明的结构的指针,或者我做错了什么?

3 个答案:

答案 0 :(得分:3)

由于它是在Test内定义的,Node是嵌套类型,即Test::Node。因此,(非内联)函数定义必须写为

Test::Node* Test::stupidFunction() {

但是,返回局部变量地址的实现严重错误。一旦函数返回,变量(此处为foo就会超出范围,因此调用者会留下错误的指针。

一个选项是以下

Test::Node* Test::stupidFunction() {
  Node * pNode = new Node;
  // update pNode
  return pNode;
}

但是,这个设计也有一个问题,调用者必须确保返回指针在delete之前 - 在它超出范围之前。否则new Node分配的内存将被泄露。

更好的选择是使用智能指针

std::shared_ptr<Test::Node> Test::stupidFunction() {
  auto pNode = std::make_shared<Test::Node>();
  // update pNode;
  return pNode;
}

这样,调用者不需要显式delete。只要没有指向该资源的指针即Node,就会释放内存。

答案 1 :(得分:1)

struct节点在Test Class中定义

class Test{
private:
    struct Node{
        int element;
        Node* next;
    };

    Node* stupidFunction(); // Line 8
};

///////////////////////////////

struct Node;

Test::Node* Test::stupidFunction(){ //use Node which define in class Test
    Node foo;
    return &foo;
}

int main(void)

答案 2 :(得分:0)

对于多样性,以下作品

auto Test::stupidFunction() -> Node*
相关问题