为什么标识符"v"未定义?

Why is identifier "v" undefined?

本文关键字:未定义 为什么 标识符      更新时间:2023-10-16

我对编程很陌生,我正在学习c++。我试着用向量来做这个练习,但是它们让我很困惑。我认为这段代码应该工作,但我不知道为什么我的IDE说v是未定义的。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
class check_input
{
public:
    void checkInput();
    void getnum();
    void displaynum();

private:
    vector<int> x;
    int sum = 0;
    int n = -1;
};
void check_input::checkInput()
{
    sum = 0;
    n = -1;
}
void check_input::getnum()
{
    int x;
    cout << "Please enter the number of values you want to sum, starting with the first: ";
    cin >> n;
    if (n < 1)
    {
        cout << "the number of elements must be a positive integer" << endl;
    }
    else
    {
        cout << "Please enter some integers (press '|' to stop): ";
        while (cin >> x) v.push_back(x);
        if (v.size() < n)
        {
            cout << "too few numbers; we need " << n << endl;
        }
        else
        {
            for (int i = 0; i < n; ++i) sum += v[i];
        }
    }
}

void check_input::displaynum()
{
    cout << "The sum of the first " << n << " numbers ( ";
    for (int i = 0; i < n; ++i) cout << v[i] << ' ';
    cout << ") is " << sum << 'n';
}

因为你没有定义这个变量

请尝试在右作用域中定义它,这样您就不会得到IDE的错误。:)

您没有定义向量v,请在代码中添加vector<int> v;