繁体   English   中英

将值作为C中类的成员传递给vector

[英]Passing values to vector as a member of a class in C++

我想将值从主函数传递给向量,在该函数中向量被初始化为vectorEx类的成员函数:这是代码。

这样做是为了重载“ +”以添加向量的元素。

#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 ++ 11,则可以通过以下方式初始化:

vector<double> v = std::vector<double>(5);

或者,如果不能使用C ++ 11,则可以通过构造函数进行初始化:

vectorEx() : v(5) { }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM