我正在尝试编写一个记录日期的简单程序。该程序使用名为Date的Struct。 Struct中是一个参数化构造函数Date。 构造函数还确保日期大致有效(确保月份在1到12之间,日期在1到31之间)。稍后的分配解决了此类验证的问题。
在Struct中还有一个add_day函数。这是我遇到问题的地方。我似乎无法将struct变量调用到函数中来添加日期。
struct Date
{
int y, m, d;
public:
Date(int y, int m, int d);
void add_day(int n);
int month()
{
return m;
}
int day()
{
return d;
}
int year()
{
return y;
}
};
/// main program calls the struct and add day function with parameters.
int main()
{
Date today(1978, 6, 26);
today.add_day(1);
keep_window_open();
return 0;
}
// Function definition for the Constructor. Checks values to make sure they
are dates and then returns them.
Date::Date(int y, int m, int d)
{
if ((m < 1) || (m > 12))
cout << "Invalid Month\n";
if ((d < 1) || (d > 31))
cout << "Invalid Day\n";
else
y = y;
m = m;
d = d;
cout << "The date is " << m << ',' << d << ',' << y << endl;
// This function will accept the integers to make a date
// this function will also check for a valid date
}
void Date::add_day(int n)
{
// what do I put in here that will call the variables in Date to be
// modified to add one to day or d.
};
答案 0 :(得分:2)
您只需通过命名它们就可以在其成员函数中引用类的成员变量,例如:
void Date::add_day(int n)
{
d += n;
}
此处,d
会引用您在代码段顶部声明的int d
成员变量:
struct Date
{
int y, m, d;
// ...
}
但是,成员变量的阴影可能让您感到困惑。此外,请注意您有其他设计问题以及几种可以改进代码的方法。看一下这个版本的灵感:
#include <iostream>
#include <stdexcept>
class Date
{
int year_, month_, day_;
public:
explicit Date(int year, int month, int day)
: year_(year), month_(month), day_(day)
{
if (month_ < 1 || month_ > 12)
throw std::logic_error("Invalid Month");
if (day_ < 1 || day_ > 31)
throw std::logic_error("Invalid Day");
}
void add_days(int days) { /* ... */ }
int year() const { return year_; }
int month() const { return month_; }
int day() const { return day_; }
};
std::ostream & operator<<(std::ostream & os, const Date & date)
{
return os << date.year() << '-' << date.month() << '-' << date.day();
}
int main()
{
Date date(1978, 6, 26);
date.add_days(1);
std::cout << date << '\n';
return 0;
}
答案 1 :(得分:-1)
成员函数和构造函数中的成员变量可以通过引用它们的名称(y, m, d
)或显式地使用this
指针(this->y, this->m, this->d
)隐式访问。
例如,添加一天:
void Date::add_day(int n)
{
d += n; // Modifies the 'd' member variable
// ... below here we must handle what
// happens when the number of days exceeds t
// he number of days in the particular month.
};
构造函数中也存在问题。因为构造函数的参数变量与成员变量共享相同的名称。例如:
m = m;
d = d;
通过这些赋值,编译器将假定您将本地参数变量赋值给local参数变量。所以你实际上根本没有为成员变量分配任何值。一种解决方案是明确指定它们如下:
this->m = m;
this->d = d;
y
变量也是如此。