Tho*_*mas 122 c++ static initialization constants
我上课了
class foo {
public:
foo();
foo( int );
private:
static const string s;
};
Run Code Online (Sandbox Code Playgroud)
在s
源文件中初始化字符串的最佳位置在哪里?
squ*_*art 171
港九一个编译单元(通常.cpp文件)会做:
foo.h中
class foo {
static const string s; // Can never be initialized here.
static const char* cs; // Same with C strings.
static const int i = 3; // Integral types can be initialized here (*)...
static const int j; // ... OR in cpp.
};
Run Code Online (Sandbox Code Playgroud)
Foo.cpp中
#include "foo.h"
const string foo::s = "foo string";
const char* foo::cs = "foo C string";
// No definition for i. (*)
const int foo::j = 4;
Run Code Online (Sandbox Code Playgroud)
(*)根据标准,如果在代码中使用它而不仅仅是整数常量表达式,则必须i
在类定义之外定义(如j
is).有关详细信息,请参阅下面David的评论.
Mic*_*urr 12
静态成员需要在文件范围或适当的命名空间中的.cpp转换单元中初始化:
const string foo::s( "my foo");
Run Code Online (Sandbox Code Playgroud)
ple*_*ndo 12
从 C++17 开始,内联说明符也适用于变量。您现在可以在类定义中定义静态成员变量:
#include <string>
class foo {
public:
foo();
foo( int );
private:
inline static const std::string s { "foo" };
};
Run Code Online (Sandbox Code Playgroud)
GMa*_*ckG 10
在同一名称空间内的翻译单元中,通常位于顶部:
// foo.h
struct foo
{
static const std::string s;
};
// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives
// bar.h
namespace baz
{
struct bar
{
static const float f;
};
}
// bar.cpp
namespace baz
{
const float bar::f = 3.1415926535;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
153426 次 |
最近记录: |