我想从主函数将值传递给 vector ,其中 vector 被初始化为 vectorEx 类的成员函数: 这是代码。
这样做是为了尝试重载“+”以添加 vector 元素。
#include <iostream>
#include <vector>
using namespace std;
class vectorEx
{
public:
vector<double> v(5);
static const int m = 5;
};
int main()
{
vectorEx a;
cout << a.m << endl;
(a.v).at(0) = 5;
return 0;
}
我得到的错误是:
vectorInsideClasses.cpp:9:20: error: expected identifier before numeric constant
vectorInsideClasses.cpp:9:20: error: expected ‘,’ or ‘...’ before numeric constant
vectorInsideClasses.cpp: In function ‘int main()’:
vectorInsideClasses.cpp:22:7: error: ‘a.vectorEx::v’ does not have class type
这不像 Java 中的方法链吗?
例如在Java中:System.out.println("Hello")
,与(System.out).println("Hello")
是一样的
最佳答案
C++ 不允许您像那样初始化类中的非静态成员相当。官方的方式是这样的:
vector<double> v = vector<double>(5);
不幸的是,Microsoft Visual Studio 尚不支持像这样在主体中初始化非静态成员,因此您必须使用构造函数。
class vectorEx
{
public:
vector<double> v;
static const int m = 5;
vectorEx() //the default constructor
: v(5) //initialize the non-static member
{
}
};
关于c++ - 在 C++ 中将值作为类的成员传递给 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23795565/