我正在使用 GCC 4.8.2:
$ g++ --version
g++ (GCC) 4.8.2
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
我有这个类定义:
#pragma once
#include "SpreadsheetCell.h"
class Spreadsheet
{
public:
Spreadsheet(int inWidth, int inHeight);
Spreadsheet(const Spreadsheet& src);
~Spreadsheet();
int getId() const;
int getWidth() const;
int getHeight() const;
void setCellAt(int x, int y, const SpreadsheetCell& cell);
SpreadsheetCell getCellAt(int x, int y) const;
Spreadsheet& operator=(const Spreadsheet& rhs);
private:
bool inRange(int val, int upper) const;
void copyFrom(const Spreadsheet& src);
void freeMemory();
int mWidth, mHeight, mId;
SpreadsheetCell** mCells;
static int sCounter = 0;
};
当我尝试编译它时,我得到:
$ make SpreadsheetTest && SpreadsheetTest
g++ -Wall -g -std=c++11 -c Spreadsheet.cpp
In file included from Spreadsheet.cpp:3:0:
Spreadsheet.h:27:31: error: ISO C++ forbids in-class initialization of non-const static member ‘Spreadsheet::sCounter’
static int sCounter = 0;
^
Makefile:11: recipe for target 'Spreadsheet.o' failed
make: *** [Spreadsheet.o] Error 1
奇怪的是,如果我static
从声明中删除修饰符sCounter
,它会正常编译。
到底是怎么回事?
编辑:
自 GCC 4.7 起,此功能似乎可用:http: //gcc.gnu.org/projects/cxx0x.html
编辑2:
我正在尝试找到官方参考,但我从 Gregoire、Solter & Kleper 的“Professional C++”-第 2 版一书中获取了这段代码(第 7 章,第 181 页,“静态数据成员”小节)和它应该工作。
使用 C++11,这就是您需要做的所有事情。如果您使用 C++ pior to C++11,它会有点笨拙 [...]
然后它建议我做传统的方式。
作者错了吗?