注册 登录
编程论坛 C++教室

这个错误提示怎么回事

小旭哥 发布于 2012-11-09 13:19, 583 次点击
class Date
{
public:
    static const int monthsPerYear = 12;
    Date( int = 1, int = 1, int = 1900 );
    void print() const;
    ~Date();

private:
    int month;
    int day;
    int year;

    int checkDay( int ) const;
};

我把这个类的定义放在头文件里,我是用静态链接库来写类的,当我build工程时, 出现如下错误
d:\个人资料\c++\classes\class.h(47) : error C2258: illegal pure syntax, must be '= 0'
d:\个人资料\c++\classes\class.h(47) : error C2252: 'monthsPerYear' : pure specifier can only be specified for functions

我确定是   static const int monthsPerYear = 12;  这里出问题了  因为我把它注释后就没有问题了,不知道哪里错了,以及为什么。怎么改
10 回复
#2
liman1232012-11-09 14:10
能把整段代码贴一下吗?估计应该是静态变量没用常函数去调用。
#3
小旭哥2012-11-09 17:28
回复 2楼 liman123
我这只是类的定义  没别的代码了   我放在头文件里的
#4
yuccn2012-11-09 22:35

这样肯定是不行的,这个是类的声明,
class Date
 {
 public:
     static const int monthsPerYear;
……
……
 };

static const int Date::monthsPerYear = 12;
Date:: Date(int d, int m, int y )
{
……
}

注意,在cpp中 对静态const初始化

 


[ 本帖最后由 yuccn 于 2012-11-9 22:38 编辑 ]
#5
zjf_to2012-11-10 12:20
static const int monthsPerYear = 12;这个写法是没有错的吧,你是不是用vc6.0的呢??
#6
liman1232012-11-10 12:53
类中的静态变量的初始化只能这类的实现文件中!即类的定义之外.
#7
liman1232012-11-10 12:53
四楼说的对。
#8
天剑山2012-11-10 14:21
class Date
{
public:
    static const int monthsPerYear;
    Date( int = 1, int = 1, int = 1900 );
    void print() const;
    ~Date();

private:
    int month;
    int day;
    int year;

    int checkDay( int ) const;
};

static const int Date::monthsPerYear = 12;
这个要放在外面
#9
小旭哥2012-11-13 16:24
回复 4楼 yuccn
我是用类的定义和实现放写静态库里的,是在那个写库的cpp文件里初始化静态变量么,还是在用户程序中初始化?
#10
小旭哥2012-11-13 16:25
回复 6楼 liman123
那怎么告诉编译器,我这个静态变量是这个类的呢?
#11
liufashuai2012-11-14 21:31
静态变量初始化放在类外面,前面的域作用符告诉编译器这个静态变量属于前面的类
1