初学者

王朝vc·作者佚名  2006-01-08
宽屏版  字体: |||超大  

今天在读《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;

}

一切OK

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
>>返回首页<<
推荐阅读
 
 
频道精选
© 2005- 王朝网络 版权所有