在类中传递私有变量——为什么不允许这样做
Passing Private Variables in Classes - Why Is This Not Allowed?
我有这样一个类:
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_february
在after_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
来解决这个问题。
相关文章:
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 为什么我的变量没有更新,我的 LED 没有亮起?
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 为什么C++有不同的变量初始化方式?
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 为什么未命名的结构内联变量在每个翻译单元中没有相同的地址?
- 为什么我可以将变量存储在不是其最小对齐方式的倍数的地址?
- 为什么thread_local变量在这里从未初始化?
- 为什么内存屏障依赖于变量?
- 为什么我的变量存在于其范围之外
- 为什么我们再次从结构对象创建结构变量?
- 字符串与字符* 作为类成员变量.为什么要使用字符*
- 如何读取文件内容并将其保存到字符串类型变量?为什么有空白空间
- 将char * *变量赋值给char * const *变量——为什么允许这样做?
- 在类中传递私有变量——为什么不允许这样做
- 引用临时变量 - 为什么编译器没有检测到它?
- 访问类中的私有成员变量:为什么这样做
- 全局变量-C++为什么这种方式很危险
- ' ios_base '的标志都是静态const整型变量.为什么可以用' ios_base::setf() '来