为什么我不能在类中初始化非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) C++ 11支持新的函数语法:
auto func_name(int x, int y) -> int;
Run Code Online (Sandbox Code Playgroud)
目前此函数将声明为:
int func_name(int x, int y);
Run Code Online (Sandbox Code Playgroud)
新风格似乎还没有被广泛采用(比如在gcc stl中)
但是,这种新风格是否应该在新的C++ 11程序中随处可见,还是仅在需要时使用?
就个人而言,我更喜欢旧款式,但是混合风格的代码库看起来很丑陋.
我得到了成员变量'objectCount'的资格错误.编译器还返回'ISO C++禁止非const静态成员的类内初始化'.这是主要类:
#include <iostream>
#include "Tree.h"
using namespace std;
int main()
{
Tree oak;
Tree elm;
Tree pine;
cout << "**********\noak: " << oak.getObjectCount()<< endl;
cout << "**********\nelm: " << elm.getObjectCount()<< endl;
cout << "**********\npine: " << pine.getObjectCount()<< endl;
}
Run Code Online (Sandbox Code Playgroud)
这是包含非const静态objectCount的树类:
#ifndef TREE_H_INCLUDED
#define TREE_H_INCLUDED
class Tree
{
private:
static int objectCount;
public:
Tree()
{
objectCount++;
}
int getObjectCount() const
{
return objectCount;
}
int Tree::objectCount = 0;
}
#endif // TREE_H_INCLUDED
Run Code Online (Sandbox Code Playgroud)