3

I have a tiny .h file:

#include "stdafx.h" #ifndef BIGNUM_H #define BIGNUM_H #include <vector> class bignum{ private: std::vector<int> num; num.resize(4); }; #endif 

I get the following error messages:

  • excepted type speciefier
  • this declaration has no storage class or type specifier

What am I missing?

3
  • 3
    The vector declaration is OK. The resize is wrong. Commented Jul 14, 2013 at 18:19
  • possible duplicate of Declaring vectors in a C++ header file Commented Jul 14, 2013 at 18:20
  • 2
    @Mgetz, No, this is a different question Commented Jul 14, 2013 at 18:24

2 Answers 2

11

You can't call a method on a member variable inside your class declaration. If you want to resize the vector to 4 do so in the class constructor (or in another function but the constructor is by far the best place to do so).

In your cpp file you could do something like:

bignum::bignum() { num.resize(4); } 

or:

bignum::bignum(): num(4) {} 

The second one calls the vector constructor that takes a size argument. Or you can directly do it in your .h file:

class bignum{ bignum(): num(4) {} // version 1 bignum(): num() { num.resize(4); } // version 2 private: std::vector<int> num; }; 
Sign up to request clarification or add additional context in comments.

Comments

4

You cannot call num.resize(4); outside of a function. You could use your class' constructor, or a C++11 initialization at the point of declaration.

class bignum { private: std::vector<int> num = std::vector<int>(4); // C++11 }; class bignum { bignum() : num(4) {} // C++03 and C++11 private: std::vector<int> num; }; 

5 Comments

I got the error message: excepted a ; If I use the form std::vector<int> num{4};
@user2351645 do you have the relevant C++11 support? You need that, obviously.
It should create a vector with the size 4. As I know.
@user2351645, No, that creates a vector with one element - 4.
@user2351645 there was an error in my original answer. I fixed it in an edit.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.