【问题标题】:C++: run-time error from a template classC++:来自模板类的运行时错误
【发布时间】:2016-09-07 14:06:50
【问题描述】:

大家好,我的程序有问题。我是 C++ 新手,我正在尝试编写通用编程代码,但是像往常一样,我的程序有很多错误。 我正在尽我最大的努力,但我不明白我的错误在哪里。 我想要一个模板类,我在其中描述了一个求和的方法 add(),c'tor 和 compute() 对总和进行算术平均。 nAdd 是元素的数量。非常感谢!

template<typename T>
class AccumulatorMean {
    public:

        AccumulatorMean() : sum(0), nAdd(0), media(0) {};
        T add(const T& data);
        T compute();
private:
        int nAdd;
        T sum;
        T media;
};

template <typename T>
T& AccumulatorMean::add(const T& data) {
    sum += data;
    nAdd++;
    return sum;
}
template <typename T>
T& AccumulatorMean::compute() {
    media = sum/nAdd;
    return media;
}
int main() {
    AccumulatorMean a;
    a.add<int>(5);
}

【问题讨论】:

  • 只是给您的信息:当您在编译过程中遇到错误时,它是compile time error。当您实际运行程序并出现错误时,它是runtime error

标签: function class templates c++11


【解决方案1】:

这里有一些错误:

第一:

你的 main 应该是这样的:

int main() {
    AccumulatorMean<int> a;
    a.add(5);
}

您指定类具有模板参数。所以你必须在实例化类时添加它。

第二:

当您使用模板参数定义类的成员函数时,也必须添加此参数:

template <typename T>
T AccumulatorMean<T>::add(const T& data) {
    ...
}

AccumulatorMean&lt;T&gt;

第三个:

在您的代码中,函数的定义返回 T&amp;,而您声明它们返回 T。那也是错误的。我已经在我的代码中更改了上面的内容。

【讨论】:

    猜你喜欢
    • 2010-10-18
    • 1970-01-01
    • 2015-08-05
    • 2012-10-04
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    相关资源
    最近更新 更多