[英]compiler not recognizing vector as class member
enter image description here I am trying out some STL programs. 在这里输入图像描述,我正在尝试一些STL程序。 I have declared a vector in main and tried to run the program it is working but if i declare the same(vector) inside the class then am getting a compilation error.
我已经在main中声明了一个vector,并试图运行程序,该程序正在运行,但是如果我在类内声明了same(vector),则会出现编译错误。 I think compiler is not recognizing vector(declared inside the class).
我认为编译器无法识别向量(在类内部声明)。
I have tried with std:: also still same error. 我已经尝试过std ::也仍然是相同的错误。 I am using netbeans IDE and cigwin compiler.
我正在使用netbeans IDE和cigwin编译器。
please find the code below 请在下面找到代码
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cctype>
using namespace std;
/*
*
*/
class vectorcl
{
vector<int> v(10);
int i;
public:
vectorcl();
void add_vector();
void dis_vector();
};
vectorcl :: vectorcl()
{
for(i =0;i<10 ;i++)
{
v[i] = 0;
}
}
void vectorcl :: dis_vector()
{
cout<< " The vale is : \n";
for(i =0;i<10 ;i++)
{
cout << "\t " <<v[i];
}
}
void vectorcl :: add_vector()
{
for (i =0 ; i<10; i++)
{
v[i] = i+1;
}
}
int main(int argc, char** argv) {
// vector<int> vp(10);
// for(int j =0;j<10 ;j++)
// {
// cout << " " << vp[j];
// }
vectorcl v1;
v1.dis_vector();
v1.add_vector();
v1.dis_vector();
return 0;
}
Please help me in this, my question is why my compiler is not recognizing vector declared inside a class. 请帮助我,我的问题是为什么我的编译器无法识别类中声明的向量。
error : expected identifier before numeric constant expected ',' or '...'before numeric constant 错误:数字常量之前的预期标识符预期数字常量“,”或“ ...”之前
You can not use vector<int> v(10);
您不能使用
vector<int> v(10);
as member variable. 作为成员变量。 The solution is to replace it by
vector<int> v;
解决方案是用
vector<int> v;
替换它vector<int> v;
and add this alter the constructor like this: 并添加如下更改构造函数:
vectorcl::vectorcl():
v(std::vector<int>(10,0/* This 0 is instead of the for-loop*/)){
}
Or another option is to declare it as : 或另一种选择是将其声明为:
std::vector<int> v = std::vector<int>(10);
PS there is no need to declare int i as class member. PS没有必要将int i声明为类成员。 Just declare it in every function you need.
只需在您需要的每个函数中声明它即可。
From first glance, you are trying to call the constructor in the class prototype: vector<int> v(10);
乍一看,您试图在类原型中调用构造函数:
vector<int> v(10);
. 。 Your constructor for that class will be called in your wrapper class constructor unless you use a member initialization list.
除非您使用成员初始化列表,否则将在包装类构造函数中调用该类的构造函数。
Edit: using member initialization 编辑:使用成员初始化
vectorcl :: vectorcl(): v(10)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.