标题:这个 init()成员函数中总显示 y,m,d 未定义的错误(VS2013)
取消只看楼主
liu229118351
Rank: 3Rank: 3
等 级:论坛游侠
帖 子:83
专家分:101
注 册:2013-10-23
结帖率:100%
已结贴  问题点数:30 回复次数:3 
这个 init()成员函数中总显示 y,m,d 未定义的错误(VS2013)
书上的一个程序,书上的解释跟这个实际情况不一样啊。。

程序代码:
#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;
}
2014-11-11 12:16
liu229118351
Rank: 3Rank: 3
等 级:论坛游侠
帖 子:83
专家分:101
注 册:2013-10-23
得分:0 
init()真的不需要参数传递么?我试过改一下init(),给了传递参数就没问题了。。

单曲循环,需要信心+耐心+恒心
2014-11-11 12:52
liu229118351
Rank: 3Rank: 3
等 级:论坛游侠
帖 子:83
专家分:101
注 册:2013-10-23
得分:0 
回复 3 楼 beyondyf
3Q,是作用域的问题吧?构造函数调用init函数的时候init函数的作用于里面根本就没有y,m,d,然后就出现未定义吧,而init又是类的成员函数,所以成员变量还是可以用的。(不知道说的对不对)

单曲循环,需要信心+耐心+恒心
2014-11-11 17:17
liu229118351
Rank: 3Rank: 3
等 级:论坛游侠
帖 子:83
专家分:101
注 册:2013-10-23
得分:0 
回复 6 楼 stop1204
= =:刚去查了下才知道C++中的exit()的函数原型在cstdlib中。。。

单曲循环,需要信心+耐心+恒心
2014-11-13 20:05



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-438426-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.162758 second(s), 9 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved