gpt4 book ai didi

c++ - 在 C++ 类中定义静态字符串变量

转载 作者:太空狗 更新时间:2023-10-29 20:16:27 26 4
gpt4 key购买 nike

我有两个问题:

为什么这对于 int 变量是可能的:

foo.h:

class foo{

private:
const static int a = 42;
};

但对于字符串变量我需要这样做吗?

foo.h:

class foo{

private:
static string fooString;
};

foo.cpp:

string foo::fooString = "foo";

还有:

在我的特殊情况下,foo::fooString 应该代表一个路径变量,我希望对于 foo 类的每个对象,只有一个 foo::string 实例,代表一个永远不会改变的 const 值。

还有其他方法可以解决这个问题吗?

最佳答案

Why is this possible for an int variable: [..] but for a string variable I need to do it this way?

只是因为。实际上你仍然可以使 string const 但是,是的,你必须在类定义之外定义它。您只能在 static 成员为 const 和整数(或“文字类型”)时对其进行就地初始化。

(在 C++11 中,当非 staticconst 成员是文字类型时,您甚至可以这样做。)

I would like that for every object of class foo there were just one instance of foo::string, representing a const value that should never change. Is there another way to solve this problem?

static const std::string,如您所料。

// C++03
struct T {
static const std::string foo;
};

const std::string T::foo = "lol";

关于c++ - 在 C++ 类中定义静态字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9497134/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com