【问题标题】:What is the correct syntax for the method returning a struct?返回结构的方法的正确语法是什么?
【发布时间】:2018-08-12 19:32:36
【问题描述】:

有人可以帮助我如何让这种方法发挥作用吗?

// At .h file
template<typename T>
class BTree {
public:
    ...
private:
    struct Node {
        T element;
        Node* left, right;
    };
    Node* root;
    Node* getNode();
    ...
};

// At .cpp file
template<typename T>
BTree<T>::BTree() {
   ...
}
// I am stuck on how I would get the getNode() method to work
// I know it's along the lines of...
template<typename T>
BTree::Node* BTree<T>::getNode() {
    ...
}

我不断收到编译错误。有正确的方法吗?

编辑:我的错误。我忘了把&lt;T&gt;放在.cpp文件里

【问题讨论】:

  • 我很乐意帮助你。但是您实际上并没有指定错误。而且您没有提供代码,我们只需复制粘贴即可得到完全相同的错误。您可以尝试修复BTree:: ---> BTree&lt;T&gt;::。除此之外,创建一个minimal reproducible example。
  • 在BTree::Node 中,符号BTree 不是类型名称,它是一个可用于创建类型的模板,如果您提供模板参数.
  • 等等,CPP 文件?你应该知道templates better be implemented in headers

标签: c++ class syntax


【解决方案1】:

您不应该在 header/cpp 文件中拆分模板内容。这是行不通的,因为您需要编译所有已知 T 的 cpp 文件。所以这里只写header only代码。

返回类型“指向嵌套类的指针”在声明前需要一个typename,因为它本身有一个模板参数。

template<typename T>
class BTree {
public:
private:
    struct Node {
        T element;
        Node* left, right;
    } localNode;   // if you want to have an instance of node in your object
    Node* root;
    Node* getNode();
    BTree();                 // <- you forget the declaration
};  

template<typename T>
BTree<T>::BTree() {
}   
// I am stuck on how I would get the getNode() method to work
// I know it's along the lines of...
template<typename T>
typename BTree<T>::Node* BTree<T>::getNode() { // <- needs typename!
    return new BTree<T>::Node;               // <- simply return the value
    // or 
    return &localNode; // if you have an instance, simply return the address
}   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多