在C++中初始化私有静态数据成员的最佳方法是什么?我在头文件中尝试了这个,但它给了我奇怪的链接器错误:
class foo
{
private:
static int i;
};
int foo::i = 0;
Run Code Online (Sandbox Code Playgroud)
我猜这是因为我无法从课外初始化私人成员.那么最好的方法是什么?
我想static const char在班上有一个数组.海湾合作委员会抱怨并告诉我应该使用constexpr,虽然现在它告诉我这是一个未定义的参考.如果我使数组成为非成员,那么它将编译.到底是怎么回事?
// .hpp
struct foo {
void bar();
static constexpr char baz[] = "quz";
};
// .cpp
void foo::bar() {
std::string str(baz); // undefined reference to baz
}
Run Code Online (Sandbox Code Playgroud) 我希望以下程序一直返回0.但是,对于Visual Studio 2013(Update 4),程序在发布版本中退出1.我不确定这是一个错误,还是编译器的优化器是正确的,并且依赖于某些边缘行为.如果关闭CONST宏,则release exe返回0.如果优化器确实正确,我是否可以获得允许它发出代码的原因?
#if 1
# define CONST const
#else
# define CONST
#endif
class TypeId {
public:
bool operator== (TypeId const & other) const
{
return id == other.id;
}
private:
TypeId (void const * id)
: id(id)
{}
public:
template <typename T>
static TypeId Get ()
{
static char CONST uniqueMemLoc = 0;
return TypeId(&uniqueMemLoc);
}
private:
void const * id;
};
int main(int, char **)
{
typedef int A;
typedef unsigned int B;
if (TypeId::Get<A>() …Run Code Online (Sandbox Code Playgroud) 我很难理解这段代码(C++ 14草案标准[conv.lval]中的一个例子)是如何调用未定义的行为的g(false).为什么constexpr让程序有效?
另外,"不访问y.n" 是什么意思?在两个调用中g()我们都返回n数据成员,为什么最后一行说它不访问它?
struct S { int n; };
auto f() {
S x { 1 };
constexpr S y { 2 };
return [&](bool b) { return (b ? y : x).n; };
}
auto g = f();
int m = g(false); // undefined behavior due to access of x.n outside its
// lifetime
int n = g(true); // OK, does not access y.n
Run Code Online (Sandbox Code Playgroud) 我一直在解决黑客问题.我遇到了一个虚函数问题,我被要求创建一个名为Student的类.该类必须具有名为cur_id(当前id)的int变量.这是班级;
class Student: public Person{
public:
static int id;
Student(){
cur_id = ++id;
}
};
int Student::id = 0;
Run Code Online (Sandbox Code Playgroud)
我被要求在创建类的每个新对象时增加cur_id +1.所以,我决定增加cur_id构造函数.如您所见,我已经static int在类中声明了一个变量static int id.然后我想在课堂上用零初始化它的值.但是当我尝试它时Student::id = 0;,我无法访问id变量.我需要再次指定其数据类型,就像我再次声明变量一样int Student::id = 0;.是什么原因,为什么我需要两次声明一个静态变量?我知道这是一个新手问题,可能有一个简单的答案,但我找不到其他主题的答案.提前致谢.