I am learning C++ for the first time, and I’m going through "Understanding the C++ Programming Language, Fourth Edition, C++11". I’m having trouble getting some code to compile from an early section.
I’m creating a custom Vector class with some basic functionality using the code below:
#include <iostream>
class Vector {
public:
Vector(int s) : elem{new double[s]}, sz{s} {}
double& operator[](int i) { return elem[i]; }
int size() { return sz; }
private:
double* elem;
int sz;
};
double read_and_sum(int s) {
Vector v(s);
for (int i=0; i!=v.size(); ++i)
std::cin>>v[i]; // read into elements
double sum = 0;
for (int i=0; i!=v.size(); ++i)
sum+=v[i]; // take the sum of the elements
return sum;
}
int main() {
int sum = read_and_sum(5);
std::cout << sum;
}
When I open the terminal and use g++ to compile the file, I get some errors in my Vector class:
vector2.cpp:5:40: error: expected member name or ';' after declaration specifiers
Vector(int s) : elem{new double[s]}, sz{s} {}
^
vector2.cpp:5:25: error: expected '('
Vector(int s) : elem{new double[s]}, sz{s} {}
^
vector2.cpp:5:39: error: expected ';' after expression
Vector(int s) : elem{new double[s]}, sz{s} {}
Am I using the wrong syntax to make the Vector class? Everything in it is pretty much identical to the book.
I’ve tried changing the syntax, but continue to get errors, and I’m not really sure what to change since I’m just starting with the language. Is this a problem with the book being C++11 and my compiler doesn’t support that syntax?
>Solution :
The error message is very clear.
Change the line Vector(int s) : elem{new double[s]}, sz{s} { to Vector(int s) : elem(new double[s]), sz(s) {.
Or you can specify option -std=c++11 to adopt c++11’s new features.