Reputation: 647
Why does the explicit vector (size_type n)
form work outside of a class but not inside?
This compiles:
#include <vector>
int main() {
std::vector<int> vec_(3); // set capacity to 3
return 0;
}
But not this:
#include <vector>
class C {
public:
std::vector<int> vec_(3); // set capacity to 3
};
int main() {
return 0;
}
g++ --std=c++0x -Wall -Wextra -g a.cpp
a.cpp:5:27: error: expected identifier before numeric constant
a.cpp:5:27: error: expected ‘,’ or ‘...’ before numeric constant
Why? :(
Upvotes: 0
Views: 126
Reputation: 18465
The correct way to do this would be:
class C {
public:
C() : vec_(3) {} // set capacity to 3 in constructor initialization list
std::vector<int> vec_;
};
Upvotes: 7
Reputation: 9113
Because that's not a valid syntax in C++. The correct way would be:
#include <vector>
class C {
public:
std::vector<int> vec_;
public:
// You add a constructor and initialize member data there:
C () : vec_(3) {}
};
There are other ways to do it, but this is the most widely used and accessible one.
Upvotes: 2
Reputation: 28573
What you want is:
class C {
public:
std::vector<int> vec_;
C() : vec_(3) { }
};
This will control how vec_
is constructed when you construct a C
object.
Upvotes: 4