class Point { public: Point(int size = DefaultSize) { } private: int DefaultSize = 1024; };
illegal pure syntax, must be '= 0'
参数缺省值只能出现在函数的声明中,而不能出现在定义体中。 所以修改为 const int DefaultSize = 1024; class Point { public: Point(int size = DefaultSize); private: };
'CgetStr' : pure specifier can only be specified for functions
今天在读《Thinking in C++》时发现一个以前使用C++中const的一个当时是在读《Essential C++》中的一个示例时出现的问题的原因,在类中定义一个常量,使用VC无论如何也编译不过去。
例如:
#include <iostream>
using namespace std;
void main()
{
const int i = 56 ;
cout<<i<<endl;
}
但是我们不能在类中定义常量,有两种情况:
1、
#include <iostream>
using namespace std;
class CTemp
{
public:
const int i = 1 ;
};
void main()
{
const int i = 56 ;
cout<<i<<endl;
}
错误提示如下:
error C2258: illegal pure syntax, must be '= 0'
error C2252: 'i' : pure specifier can only be specified for functions
2、根据第一个错误,我们把i值设为0
#include <iostream>
using namespace std;
class CTemp
{
public:
const int i = 0 ;
};
void main()
{
const int i = 56 ;
cout<<i<<endl;
}
错误提示如下:
error C2252: 'i' : pure specifier can only be specified for functions
MSDN提示错误C2252如下:'identifier' : pure specifier can only be specified for functions
《C++编程思想》解释如下:因为在类对象里进行了存储空间分配,编译器不能知道const的内容是什么,所以不能把它用做编译期间的常量。这意味着对于类里的常数表达式来说,const就像它在C中一样没有作用。
在结构体中与在类中相同:
#include <iostream>
using namespace std;
struct Temp
{
const int i = 0 ;
}tem;
void main()
{
const int i = 56 ;
cout<<i<<endl;
}
解决办法是使用不带实例的无标记的枚举(enum),因为枚举的所有值必须在编译时建立,它对类来说是局部的,但常数表达式能得到它的值
#include <iostream>
using namespace std;
class CTemp
{
private:
enum{i = 0 };
};
void main()
{
const int i = 56 ;
cout<<i<<endl;
}
转自 http://hi.baidu.com/forgiveher/blog/item/da15c1b4629f56c636d3caca.html/cmtid/10c48fcf71b17c37b600c8c5
或者可以定义如下:
#include <iostream>
#include <string>
using namespace std;
class Screen
{
public:
void home(){_cursor = 0;}
void move(int ,int);
char get(){return _screen[_cursor];}
char get(int ,int );
bool checeRange(int ,int);
short height(){return _height;}
short width(){return _width;}
private:
static const int _height;
static const int _width;
string _screen;
string::size_type _cursor;
};
const int Screen::_height = 24;
const int Screen::_width = 80;