最近我见过如下例子:
#include <iostream>
class Foo {
public:
int bar;
Foo(int num): bar(num) {};
};
int main(void) {
std::cout << Foo(42).bar << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这奇怪: bar(num)意味着什么?它似乎初始化成员变量,但我以前从未见过这种语法.它看起来像一个函数/构造函数调用,但对于一个int?对我没有任何意义.也许有人可以启发我.而且,顺便说一下,还有其他类似的深奥语言功能,你永远不会在一本普通的C++书中找到它吗?
为什么我不能在类中初始化非const static成员或static数组?
class A
{
static const int a = 3;
static int b = 3;
static const int c[2] = { 1, 2 };
static int d[2] = { 1, 2 };
};
int main()
{
A a;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器发出以下错误:
g++ main.cpp
main.cpp:4:17: error: ISO C++ forbids in-class initialization of non-const static member ‘b’
main.cpp:5:26: error: a brace-enclosed initializer is not allowed here before ‘{’ token
main.cpp:5:33: error: invalid in-class initialization of static data …Run Code Online (Sandbox Code Playgroud)