读书人

成员变量的有关问题(下面程序的异常不

发布时间: 2012-03-09 16:54:57 作者: rapoo

成员变量的问题(下面程序的错误不知道怎么改)
//成员变量的问题
#include <iostream>

using namespace std;

class Year{
private:
int y;
static const int InitY = 1970;
//pure specifier can only be specified for functions

public:
Year()
{
y = InitY;
}
int year() const
{
return y;
}
void addYear(int i)
{
y = year() + i;
}
};


int main( )
{
Year y1;
Year* const py1 = new Year();

y1.addYear(1);
py1-> addYear(2);

cout < < y1.year() < < ", " < < py1-> year() < < endl;

return 0;
}

[解决办法]
class Year{
private:
int y;
static const int InitY;
//pure specifier can only be specified for functions

public:
Year()
{
y = InitY;
}
int year() const
{
return y;
}
void addYear(int i)
{
y = year() + i;
}
};

const int Year::InitY = 1970;

读书人网 >C++

热点推荐