【发布时间】:2021-01-02 13:13:34
【问题描述】:
我有一个带有模板的类stats,以便它可以灵活使用。不过,我是模板的新手,我认为它们的目的是让它在用户周围变得灵活。所以当我撞到一堵小墙时,我觉得我做错了什么。
#include <iostream>
#include <cstdio>
#include <iomanip>
template <typename T>
class stats
{
private:
int n;
T sum;
public:
stats()
{
this->n = 0;
this->sum = T();
}
void push(T a);
void print();
};
int main()
{
std::string tmp; // change type based on class type T
stats<std::string> s;
while (std::cin >> tmp) // while input is active...
{
s.push(tmp);
}
// Output & Formatting
s.print();
return 0;
}
template <typename T>
void stats<T>::push(T a)
{
this->sum += a;
++this->n;
}
template <typename T>
void stats<T>::print()
{
std::cout << std::left << std::setw(4) << "N" << "= " << n << '\n'
<< std::left << std::setw(4) << "sum" << "= " << sum << '\n';
}
来自int main(),理想情况下,我希望每次尝试不同类型时都不必自己更改 tmp。这在 C++ 中可行吗?
【问题讨论】: