C# 在 C++ 中等效于“只读”

本文关键字:只读 C++ | 更新日期: 2023-09-27 17:56:59

我有一个c#代码,其中存在一个类中的变量。

public static readonly string str;

现在我正在为这个类编写 c++ 代码。我可以在 c++ 中使用什么来做这件事static readonly

C# 在 C++ 中等效于“只读”

我认为您可以使用私有成员并为其制作getter。像这样的东西

#include <string>
class Test
{
public:
  static std::string getStr() const { return str; }
private:
  static std::string str;
}
std::string Test::str = "initial value";

希望这有帮助。

static const std::string str = "Hello";//a is explicitly static

const表示变量的名称不能用于修改其值。 static表示变量存储在静态存储中。