Pgram
Pgram

Reputation: 81

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

I would like to pass values to a vector from the main function, where the vector is initialized as a member function of vectorEx class : Here's the code.

This is done in attempt to overloading "+" to add elements of vectors.

#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;
}

The errors I get are :

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

Is this not like Method chaining in Java?

For example in Java: System.out.println("Hello"), which is the same as (System.out).println("Hello")

Upvotes: 1

Views: 122

Answers (2)

David G
David G

Reputation: 96810

Direct-initialization of a data member is not possible within the class. The compiler will confuse the parenthesis as a function declaration. If your compiler supports C++11, you can initialize this way:

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

Alternstively, if you can't use C++11 then you can initialize through the constructor:

vectorEx() : v(5) { }

Upvotes: 1

Mooing Duck
Mooing Duck

Reputation: 66932

C++ doesn't let you initialize non-static members in a class quite like that. The official way is like this:

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

Unfortunately, Microsoft Visual Studio does not yet support initializing non-static members in the body like this, so instead you have to use a constructor.

class vectorEx
{
    public:
        vector<double> v;
        static const int m = 5;

    vectorEx() //the default constructor 
        : v(5) //initialize the non-static member
    {
    }
};

Upvotes: 4

Related Questions