我非常擅长编程,而且我正在学习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';
}
答案 0 :(得分:2)
因为您没有定义该变量。
请尝试在正确范围中定义,并且不会出现IDE错误。 :)
答案 1 :(得分:1)
您没有定义向量v,将vector<int> v;
添加到您的代码