【问题标题】:How to return nested class pointer from method?如何从方法返回嵌套类指针?
【发布时间】:2014-08-21 12:56:02
【问题描述】:

我有两个类:Database 和 Node 作为嵌套类,是否可以有一个 Node 的方法返回 Node*?

我尝试将方法nextNode的返回类型设置为Node*,但出现编译错误:'Node' does not name a type

数据库.h

class Database
{
    public:
        Database();
        Database& operator+=(const Client&);
        ~Database();
    private:
        class Node //node as nested class
        {
            public:
            Node(); //ctor
            void setHead(Client*&); //add head node
            Node* nextNode(Node*&); //return new node from the end of he list
            private:
            Client* data; //holds pointer to Client object
            Node* next; //holds pointer to next node in list
        };

        Node *head; //holds the head node
};

Databse.cpp 中的nextNode 方法声明:

Node* Database::Node::nextNode(Node*& start)
{
....
....
    return current->next;
}

谢谢。

【问题讨论】:

    标签: c++ linked-list


    【解决方案1】:

    Node 嵌套在Database 中,因此需要返回类型的范围:

    DataBase::Node* Database::Node::nextNode(Node*& start)
    ^^^^^^^^^^
    

    参数已经在作用域内,所以你可以保持原样。

    【讨论】:

    • 谢谢!你能指导我一些关于嵌套类的好文档吗?
    • @Medvednic 我会浏览一些books in this list。
    【解决方案2】:

    除了 juanchopanza 的回答,C++11 的尾随返回类型允许您在范围内声明它:

    auto Database::Node::nextNode(Node*& start) -> Node* {
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多