随笔 - 1, 文章 - 0, 评论 - 0, 引用 - 0
数据加载中……

2012年9月6日

关于c++ error : passing " "as" " discards qualifiers

今天写了一段小代码,本以为正确,但运行后,就somehow ”discard qualifier“
于是猛百度,google之,找到答案,可惜正解为英语,冗长之,自己翻译半天,终于弄明白~
这里是原程序:
#include<iostream>
using namespace std;
class Date
{
      int year;
      public:
        Date(int y):year(y){}
        int get_year()
        {
          return year;
        }
      
        int  plus(const Date& p)
        {
           int total = p.get_year()+year;
           return total;
        }
}; 
int main()
{
    Date q(1000);
    Date p(2000);
    cout<<p.plus(q);
    system("pause");
}
当你一运行必然,passing `const Date' as `this' argument of `int Date::get_year()' discards qualifiers 这行字是什么意思呢?原来const Date&p,编译器认定调用 const member function,也就是不能把p调用的成员值修改,自习看get_year,只是read,并没有modify啊?按理说没有modify,但是c++编译器总是假定你可以将值修改,事实也是如此,的确可将值修改,所以与const member function不符,怎么改两种方法。第一,去掉const。第二,在get_year 后加const标记
#include<iostream>
using namespace std;
class Date
{
      int year;
      public:
        Date(int y):year(y){}
        int get_year()
        {
          return year;
        }
      
        int  plus(const Date& p) const
        {
           int total = p.get_year()+year;
           return total;
        }
}; 
int main()
{
    Date q(1000);
    Date p(2000);
    cout<<p.plus(q);
    system("pause");
}
这样就对了。
以上仅是初学者一点思考,供大家一哂~~~

posted @ 2012-09-06 22:19 Gage 阅读(19065) | 评论 (0)编辑 收藏