zoukankan      html  css  js  c++  java
  • 关于c++ error : passing " "as" " discards qualifiers

    http://www.cppblog.com/cppblogs/archive/2012/09/06/189749.html

    今天写了一段小代码,本以为正确,但运行后,就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");
    }
    这样就对了。
    以上仅是初学者一点思考,供大家一哂~~~
  • 相关阅读:
    二分图的判定 (图)
    并查集(模板)
    数独 (dfs)
    Map <STL>
    Set <STL>
    二叉搜索树的实现
    Find a way (BFS)
    根据输入的变量,执行相应的计算公式并返回结果
    检测字符串当中x与o的数目是否相等
    根据给定的数字和字符串,生成循环指定次数的字符串
  • 原文地址:https://www.cnblogs.com/mingzhang/p/11001809.html
Copyright © 2011-2022 走看看