可以在 类 中使用外部变量吗?
Possible to use extern variable in classes?
在 C++ 中,是否可以将 class 成员变量标记为 extern?
可以吗
class Foo {
public:
extern string A;
};
字符串 A 在我包含的另一个头文件中定义的位置?
如果我正确理解你的问题和评论,你正在寻找 static data members
将字段声明为static
:
// with_static.hpp
struct with_static
{
static vector<string> static_vector;
};
仅在一个 TU(±.cpp
文件)中定义:
// with_static.cpp
vector<string> with_static::static_vector{"World"};
那你就可以用了。请注意,您可以使用 class::field
和 object.field
表示法,它们都指代同一个对象:
with_static::static_vector.push_back("World");
with_static foo, bar;
foo.static_vector[0] = "Hello";
cout << bar.static_vector[0] << ", " << with_static::static_vector[1] << endl;
上面应该打印Hello, World
在 C++ 中,是否可以将 class 成员变量标记为 extern?
可以吗
class Foo {
public:
extern string A;
};
字符串 A 在我包含的另一个头文件中定义的位置?
如果我正确理解你的问题和评论,你正在寻找 static data members
将字段声明为static
:
// with_static.hpp
struct with_static
{
static vector<string> static_vector;
};
仅在一个 TU(±.cpp
文件)中定义:
// with_static.cpp
vector<string> with_static::static_vector{"World"};
那你就可以用了。请注意,您可以使用 class::field
和 object.field
表示法,它们都指代同一个对象:
with_static::static_vector.push_back("World");
with_static foo, bar;
foo.static_vector[0] = "Hello";
cout << bar.static_vector[0] << ", " << with_static::static_vector[1] << endl;
上面应该打印Hello, World