-2

显然 push_back() 不适用于我的自定义数据类 T。编译时出现以下错误:

错误:没有匹配函数调用 'Vector::push_back(int&)'</p>

有人可以向我解释为什么会这样吗?谢谢你。

#include <std_lib_facilities>
#include <numeric>
#include <vector>
#include <string>

// vector<int> userin;                                                                                                                                                                                           
// int total;                                                                                                                                                                                                    
// bool success;                                                                                                                                                                                                 

class T
{
public:
    void computeSum(vector<T> userin, int sumamount, T& total, bool& success);
    void getData(vector<T> userin);
};

template <class T>
void computeSum(vector<T> userin, int sumamount, T& total, bool& success)
{

    if (sumamount < userin.size()){
        success = true;
        int i = 0;
        while (i<sumamount){
            total = total + userin[i];
            ++i;
        }
    } else {
        success = false;
        cerr << "You can not request to sum up more numbers than there are.\n";
    }

}

template <class>
void getData(vector<T> userin)
{
    cout << "Please insert the data:\n";
    int n;

    do{
        cin >> n;
        userin.push_back(n);
    } while (n);

    cout << "This vector has " << userin.size() << " numbers.\n";
}

int helper()
{
    cout << "Do you want help? ";
    string help;
    cin >> help;
    if (help == "n" || help == "no"){
        return 0;
    }else{
        cout << "Enter your data. Negative numbers will be added as 0. Ctrl-D to finish inputing values.\n";
    }
}

int main()
{
    helper();
    getData(userin);

    cout << "How many numbers would you like to sum?";
    int sumamount;
    cin >> sumamount;
    computeSum(userin, sumamount);
    if (success = true) {
        cout << "The sum is " << total << endl;
    } else {
        cerr << "Oops, an error has occured.\n";
    }

    cout << endl;
    return 0;
}
4

2 回答 2

2

除了一些公然冒犯的问题(例如应该是template <class T>,不是template<class>)之外,真正的问题是 vector 期望你推回类型的对象T。看起来你正在阅读类型int和推动。尝试:

template <class>
void getData(vector<T> userin)
{
    cout << "Please insert the data:\n";
    T n;

    do{
        cin >> n;
        userin.push_back(n);
    } while (n);

    cout << "This vector has " << userin.size() << " numbers.\n";
}
于 2011-10-04T04:25:58.310 回答
0

问题是这一行:

userin.push_back(n);

nint在哪里。push_back 期待 T 类型的东西。

我也不确定在这种情况下 T 类的意义是什么。

于 2011-10-04T04:26:13.037 回答