【问题标题】:calling a static method from template class from other file C++从其他文件 C++ 的模板类调用静态方法
【发布时间】:2017-05-17 10:18:41
【问题描述】:

我想要一个类Sorings,在其中通过带有模板的静态方法来实现一些排序方法。我读过here 说静态模板方法应该在.h 文件中实现。这是我的代码:

排序.h

#ifndef SORTINGS_H_
#define SORTINGS_H_

template <class T>
class Sortings {
public:
    static void BubbleSort(T a[], int len, bool increasing)
    {
        T temp;
        for(int i = len-1; i >= 1; i--)
            for(int j = 0; j<= i-1; j++)
                if(increasing ? (a[j] > a[j+1]) : (a[j] < a[j+1])) {
                    temp = a[j+1];
                    a[j+1] = a[j];
                    a[j] = temp;
                }
    };
};

#endif /* SORTINGS_H_ */

排序.cpp

#include "Sortings.h"
//empty?

练习.cpp

#include <iostream>
#include "Sortings.h"
int main() {
    int a[6] = {4,5,2,11,10,16};
    Sortings::BubbleSort<int>(a,6,true);
    return 0;
}

但它返回以下错误:(这些行是这样的,因为我已经在 Practice.cpp 中注释了所有其余部分)

Description Resource    Path    Location    Type
'template<class T> class Sortings' used without template parameters PracticeCpp.cpp /PracticeCpp/src    line 41 C/C++ Problem
expected primary-expression before 'int'    PracticeCpp.cpp /PracticeCpp/src    line 41 C/C++ Problem
Function 'BubbleSort' could not be resolved PracticeCpp.cpp /PracticeCpp/src    line 41 Semantic Error
Symbol 'BubbleSort' could not be resolved   PracticeCpp.cpp /PracticeCpp/src    line 41 Semantic Error

我不明白问题出在哪里。你能帮我理解什么是错误的吗:概念上或/和句法上?

我正在运行 Eclipse Neon.3 Release (4.6.3)

【问题讨论】:

    标签: c++ templates static-methods


    【解决方案1】:
    template <class T>
    class Sortings {
    

    模板参数适用于类,而不适用于方法。所以你必须把它叫做Sortings&lt;int&gt;::BubbleSort(a,6,true);。换句话说,没有名为Sortings 的类型。相反,类型是Sortings&lt;int&gt;

    你也不需要Sortings.cpp,因为一切都在头文件中。

    虽然没有直接在问题中提出,但我认为您不需要在这里上课。命名空间内的简单模板化静态方法可以正常工作。像这样的东西:

    namespace Sorting {
    
    template<class T>
    static void BubbleSort(T a[], int len, bool increasing) {
       // ...
    }
    
    }
    

    那你可以拨打Sorting::BubbleSort&lt;int&gt;(a,6,true)

    【讨论】:

    • 谢谢。我意识到我做了什么。它有效,当然,当我将模板声明从类更改为仅方法时,我的原始代码有效。
    【解决方案2】:

    您模板化了类而不是静态方法!

    因此,您需要使用Sortings&lt;int&gt;::BubbleSort,而不是使用Sortings::BubbleSort&lt;int&gt;

    【讨论】:

      【解决方案3】:

      在调用时,您将模板添加到函数中,但您在类中声明了模板。

      Sortings::BubbleSort<int>(a,6,true);
      

      应该变成

      Sortings<int>::BubbleSort(a,6,true);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-12
        • 2019-12-15
        • 1970-01-01
        • 1970-01-01
        • 2017-10-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多