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

这个 init()成员函数中总显示 y,m,d 未定义的错误(VS2013)

liu229118351 发布于 2014-11-11 12:16, 1706 次点击
书上的一个程序,书上的解释跟这个实际情况不一样啊。。
只有本站会员才能查看附件,请 登录

程序代码:

#include<iostream>
#include<iomanip>
using namespace std;

class Date
{
    int year, month, day;
    void init();
public:
    Date(const string& s);
    Date(int y = 2000, int m = 1, int d = 1);
    bool isLeapYear() const;
    friend ostream& operator<<(ostream& o, const Date& d);
};

void Date::init()
{
    if (y > 5000 || y < 1 || m<1 || m>12 || d<1 || d>31)
        exit(1);
}

Date::Date(const string& s)
{
    year = atoi(s.substr(0, 4).c_str());
    month = atoi(s.substr(5, 2).c_str());
    day = atoi(s.substr(8, 2).c_str());
    init();
}

Date::Date(int y, int m, int d)
{
    year = y, month = m, day = d;
    init();
}

bool Date::isLeapYear() const
{
    return (year % 4 == 0 && year % 100) || year % 400 == 0;
}

ostream& operator<<(ostream& o, const Date& d)
{
    o << setfill('0') << setw(4) << d.year << '-' << setw(2) << d.month << '-';
    return o << setw(2) << d.day << '\n' << setfill(' ');
}

int main()
{
    Date c("2005-12-28");
    Date d(2003, 12, 6);
    Date e(2002);
    Date f(2002, 12);
    Date g;
    cout << c << d << e << f << g;
}
7 回复
#2
liu2291183512014-11-11 12:52
init()真的不需要参数传递么?我试过改一下init(),给了传递参数就没问题了。。
#3
beyondyf2014-11-11 12:57
init()不需要参数。但里面的y,m,d应该是year,month,day。
#4
liu2291183512014-11-11 17:17
回复 3 楼 beyondyf
3Q,是作用域的问题吧?构造函数调用init函数的时候init函数的作用于里面根本就没有y,m,d,然后就出现未定义吧,而init又是类的成员函数,所以成员变量还是可以用的。(不知道说的对不对)
#5
stop12042014-11-13 07:44
程序代码:
void Date::init()
{
    if (y > 5000 || y < 1 || m<1 || m>12 || d<1 || d>31)
        exit(1);
}

y , m , d的声明?
#6
stop12042014-11-13 07:45
exit(1);

头文件stdlib呢

[ 本帖最后由 stop1204 于 2014-11-13 07:46 编辑 ]
#7
liu2291183512014-11-13 20:05
回复 6 楼 stop1204
= =:刚去查了下才知道C++中的exit()的函数原型在cstdlib中。。。
#8
yzm5542014-12-23 13:33
#include<iostream>
#include<iomanip>
using namespace std;

class Date
{
    int year, month, day;
   
public:
    void init();
    Date(const string& s);
    Date(int y = 2000, int m = 1, int d = 1);
    bool isLeapYear() const;
    friend ostream& operator<<(ostream& o, const Date& d)
    {
       o << setfill('0') << setw(4) << d.year << '-' << setw(2) << d.month << '-'<< setw(2) << d.day << '\n' << setfill(' ');
       return o ;
    };
   
};

void Date::init()
{
   
    if (year > 5000 || year < 1 || month<1 || month>12 || day<1 || day>31)
        exit(1);
}

Date::Date(const string& s)
{
    year = atoi(s.substr(0, 4).c_str());
    month = atoi(s.substr(5, 2).c_str());
    day = atoi(s.substr(8, 2).c_str());
    init();
}

Date::Date(int y, int m, int d)
{
    year = y, month = m, day = d;
    init();
}

bool Date::isLeapYear() const
{
    return (year % 4 == 0 && year % 100) || year % 400 == 0;
}


int main()
{
    Date c("2005-12-28");
    Date d(2003, 12, 6);
    Date e(2002);
    Date f(2002, 12);
    Date g;
    cout<<c<<d<<e<<f<<g;
    return 0;
}
1