Prawn Hongs
Prawn Hongs

Reputation: 451

What does this compiler error means - "qualified-id in declaration before ‘=’ token" in C++?

I am trying to understand the usage of private const in the class. My understanding is that private const is used to make something constant within the class and static to have one copy.

Initially, my code was using pi and it's data type was float. So, I tried changing the float to int because I read const static is only allowed for int types within class.

#include <iostream>
class MyExample
{

 private:
   static const int x;

};

int main(void)
{
  int const  MyExample::x = 3;

  std::cout<<"x value is "<<MyExample::x<<std::endl;

  return 0;
}

compiling -

$g++ -std=c++14 test.cpp
test.cpp: In function ‘int main()’:
test.cpp:12:27: error: qualified-id in declaration before ‘=’ token
   int const  MyExample::x = 3;

I know that moving the line " int const MyExample::x = 3;" from main() to outside, removes error if I remove private also.

Upvotes: 2

Views: 15495

Answers (3)

Hogan Chou
Hogan Chou

Reputation: 21

I have the same problem, but when I put static member initialization out of main function, the problem is solved, like this:

int const  MyExample::x = 3;
int main(){...}

Upvotes: 2

M.M
M.M

Reputation: 141648

MyExample::x is a qualified-id and you have placed it in a declaration before the = token. This is not allowed at block scope.

Upvotes: 0

Seil Choi
Seil Choi

Reputation: 54

because the variable ' x' is private access modifier, that means variable x used only in the class. So you can't use that variable in main function.

and there is 2 suggestion.

first, make getter, setter method.

second, change to public access modifier.

thanks

Upvotes: 1

Related Questions