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");
    }
    这样就对了。
    以上仅是初学者一点思考,供大家一哂~~~
  • 相关阅读:
    java
    java
    java
    js
    java
    异常之异常处理
    面向对象之元类
    面向对象之内置方法
    面向对象之反射
    面向对象之类方法与静态方法
  • 原文地址:https://www.cnblogs.com/mingzhang/p/11001809.html
Copyright © 2011-2022 走看看