简体   繁体   English

如何使用匿名名称空间在.cpp文件中设置静态成员变量?

[英]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 我有一个包含静态成员变量的类,我想在.cpp文件中使用匿名名称空间对其进行初始化,就像在链接中看到的那样: 在C ++中的何处放置常量字符串:静态类成员或匿名名称空间

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;
  }

}

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. 由于声明,该static变量将一直存在。

The confusion might be because static has different meanings: 造成混淆的原因可能是因为static具有不同的含义:

However, a static class member doesn't have anything to do with visibility (internal/external linkage). 但是, static类成员与可见性 (内部/外部链接)无关。 Instead it has to with storage duration . 相反,它必须具有存储期限

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在.cpp文件中使用类的静态成员 - using static member of a class in .cpp file 如何在 *.cpp 文件中实现静态类成员函数? - How to implement static class member functions in *.cpp file? 如何通过仅在cpp文件中初始化静态成员的情况 - how to initialize a static member in cpp file only situation via a 如何在cpp文件中调用静态成员函数 - how to call a static member function inside a cpp file 在cpp文件中初始化私有静态成员变量。 错误:成员是私人的 - Initializing a private static member variable in the cpp file. error: member is private 如何访问在命名空间中声明的变量到另一个cpp文件中 - How to access a variable which is declare in namespace into another cpp file 如何在运行时使用静态成员函数初始化静态成员变量? - How to initialize a static member variable using a static member function at runtime? 私有 static 成员 function 还是匿名命名空间中的免费 function? - private static member function or free function in anonymous namespace? 在cpp文件的匿名命名空间中使用模板函数是否合适? - Is it proper to have a template function inside an anonymous namespace of a cpp file? c++ 在 header 中声明的私有成员与在 cpp 文件中声明的 static 变量 - c++ private member declared in header vs static variable declared in cpp file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM