user1701840
user1701840

Reputation: 1112

How to set a static member variable in the .cpp file using anonymous namespace?

I have a class that contains a static member variable, I would like to initialize it using an anonymous namespace in the .cpp file just like what I saw in the link :Where to put constant strings in C++: static class members or anonymous namespaces

But I am getting an error saying the current member rate cannot be defined in the scope. Why?

//A.h
namespace myclass
{
class A
{
   private:
      static double rate;
};
}


//A.cpp
namespace myclass
{
   namespace{
      double A::rate = 99.9;
  }

}

Upvotes: 0

Views: 245

Answers (1)

sehe
sehe

Reputation: 393849

You can't: it's already a qualified member of a class:

//A.cpp
namespace myclass
{
   double A::rate = 99.9;
}

will do. The static will already stick, because of the declaration.

The confusion might be because static has different meanings:

However, a static class member doesn't have anything to do with visibility (internal/external linkage). Instead it has to with storage duration.

Upvotes: 1

Related Questions