在类中传递私有变量——为什么不允许这样做

Passing Private Variables in Classes - Why Is This Not Allowed?

本文关键字:变量 为什么 不允许 这样做      更新时间:2023-10-16

我有这样一个类:

class Date
{
public:
    Date();                                         // Sets a date of January 1, 2000
    Date(int mm, int dd, int yyyy);                 // Sets a date with the passed arguments; automatically converts two-digit years as being AFTER the year 2000
    Date after_period_of ( int days ) const;        // Elapses an arbitrary amount of time, and returns a new date
    string mmddyy () const;                         // Returns date in MM/DD/YY format (1/1/00)
    string full_date () const;                      // Returns date in full format (January 1, 2000)
    string month_name () const;                     // Returns the name of the month as a string;
private:
    int days_in_february(int yr);
    int month;
    int day;
    int year;
};

当我尝试将私有变量year作为参数传递给days_in_february时,我得到以下错误消息:

passing ‘const Date’ as ‘this’ argument of ‘int Date::days_in_february(int)’ discards qualifiers

days_in_februaryafter_period_of中称为

Date Date::after_period_of (int days_elapsed) const
{
    int new_month;
    int new_year = year;    // tried copying 'year' to get around this issue, but it did not help
    int days_into_new_month;
    int max_days_in_month[12] =  { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } ;
    max_days_in_month[1] = days_in_february(new_year);

在同一个函数中
if (new_month == 13)
            {
                new_month = 1;
                new_year += 1;
                max_days_in_month[1] = days_in_february(new_year);
            }

days_in_february只是根据传入的年份返回数字28或29。它不试图操作自己的块之外的任何东西。

我甚至试图传递一个非编程变量到它(days_in_february(2000)),我得到同样的错误。我试过把这个功能移到公共领域,但也没能解决这个问题。

为什么会发生这种情况?

为什么不允许我这样做?

after_period_of内部,不能访问非常量函数;特别是,您不能访问days_in_february。可以通过声明后一个函数const来解决这个问题。