Question

When I compile the following code:

#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
namespace ublas = boost::numeric::ublas;
class Point {
    ublas::vector<double> v(3);
}

I get this error below complaining about the value 3 being in the constructor. The boost example code itself shows the size of the vector being initialized with the constructor.

g++ -std=c++11 -w -I/usr/local/Cellar/boost/1.55.0/include -L/usr/local/Cellar/boost/1.55.0/ -l -lboost_system   -c -o point.o point.cc
point.cc:38:29: error: expected parameter declarator
ublas::vector<double> v(3);
                        ^
point.cc:38:29: error: expected ')'
point.cc:38:28: note: to match this '('
ublas::vector<double> v(3);

If I instead run it with an empty constructor like this

    ublas::vector<double> v();

then it runs fine. Somewhere I'm making a mistake because the BOOST example code looks like this.

#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>

int main () {
    using namespace boost::numeric::ublas;
    vector<double> v (3);
    for (unsigned i = 0; i < v.size (); ++ i)
        v (i) = i;
    std::cout << v << std::endl;
}

I imagine it's somewhere in my make file or something though I'm not really sure what.

My entire Makefile looks like this:

CXX=g++
CXXFLAGS=-std=c++11 -w -I/usr/local/Cellar/boost/1.55.0/include -L/usr/local/Cellar/boost/1.55.0/ -l -lboost_system
BIN=orange

SRC=$(wildcard *.cc)
OBJ=$(SRC:%.cc=%.o)

all: $(OBJ)
    $(CXX) -o $(BIN) $^

%.o: %.c
    $(CXX) $@ -c $< 

clean:
    rm -f *.o
    rm -f $(BIN)

Any help would be greatly appreciated.
Thanks in advance,
Max

Was it helpful?

Solution

Non-static data member initialization at the point of declaration does not support () syntax, since in this form it can be confused with a function declaration. So you need

class Point {
    ublas::vector<double> v = ublas::vector<double>(3);
};

Note that this is a valid initialization too:

class Point {
    ublas::vector<double> v{3};
};

But if this vector has a constructor that takes an initialization_list (like std::vector does), it would initialize v to have one element of value 3.0.

Alternatively, you can use C++03 style and initialize in the constructor initialization list. But note that in this case your class is no longer an aggregate. This may or may not be an issue. Example:

class Point {
 public:
    Point() : v(3) {}
 private:
    ublas::vector<double> v;
};

Also, note the trailing ;.

OTHER TIPS

It's because you declare a member variable in a class. That means you have to initialize the variable in the constructors initializer list:

class Point {
    ublas::vector<double> v;

    Point() : v(3) {}
};

Also note that when you do

ublas::vector<double> v();

you are declaring a function v that takes no arguments and returns a vector.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top