对于static
关键字在C ++中的工作方式,我似乎有一些误解。具体来说,我需要了解以下代码的问题:
#include <iostream>
struct A{
int a;
A(int ain) : a(ain) { }
A() : a(1) { }
static A getA()
{
return A(2);
}
};
struct B
{
static A a = A::getA();
};
int main() {
std::cout << B::a.a << std::endl;
}
如果static
按预期工作,上面的代码示例将2
正常打印并退出-相反,我收到以下编译器错误消息:
g++ -c -o syntax.o syntax.cpp
syntax.cpp:17:21: error: ‘A::getA()’ cannot appear in a constant-expression
static A a = A::getA();
^
syntax.cpp:17:26: error: a function call cannot appear in a constant-expression
static A a = A::getA();
^
syntax.cpp:17:26: error: invalid in-class initialization of static data member of non-integral type ‘A’
syntax.cpp:17:26: error: initializer invalid for static member with constructor
syntax.cpp:17:26: error: (an out of class initialization is required)
syntax.cpp:17:26: error: ‘B::a’ cannot be initialized by a non-constant expression when being declared
make: *** [syntax.o] Error 1
阅读错误消息后,我意识到static
我尚不了解其中的某些内容,但是我发现很难查明是什么。可能是因为我在Java和C#等语言中做了很多工作,它们也有static
关键字,但显然在工作方式上有所不同。
有人可以告诉我为什么上面的代码无效吗?
静态成员功能
有两种方法可以调用给定的静态成员函数T
:
您使用范围解析运算符::
,或者
您可以T
使用operator.
(在变量上调用其他任何成员函数)在上述类型的实例上调用它。
法律架构
struct Obj {
static void func () {
/* ... */
}
};
以下两个两个片段调用静态成员函数func
中Obj
。
Obj a; a.func ();
Obj::func ();
违法建筑
Obj a;
Obj.func (); // illegal, `Obj` is a type and not an instance
a ::func (); // illegal, `a` is an instance of `Obj`, not a type
静态数据成员
static
数据成员用于声明在给定类型的每个实例之间共享的变量。
在问题提供的代码段中,您尝试使用更正后的返回值初始化a
类型为的静态数据成员。不允许这样做,因为尝试初始化数据成员而不使其成为类内初始化的非法构造。A
A::getA ()
static
constexpr
struct B {
static A a = A::getA(); // illegal, `static A a` is not `constexpr`
};
有关静态数据成员的类内初始化的更多信息,请参见:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句