C 成员功能

C++ Member Functions

本文关键字:功能 成员      更新时间:2023-10-16

我正在尝试编写一个记录日期的简单程序。该程序使用称为日期的结构。结构内是参数化的构造函数日期。构造函数还确保日期大致有效(确保月份在1到12之间,并且天数在1-31之间(。后来的分配解决了此类验证的问题。

在结构内也是一个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 Monthn";
    if ((d < 1) || (d > 31))
        cout << "Invalid Dayn";
    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.
};

您可以通过命名,例如:

来参考其成员函数中类的成员变量
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;
}

构件变量可以在成员函数和构造函数中通过其名称(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;

使用这些作业,编译器将假设您的意思是将本地参数变量分配给本地参数变量。因此,您实际上根本没有分配成员变量任何值。一种解决方案是明确指定它们如下: this->m = m; this->d = d; y变量也是如此。