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");
    }
    这样就对了。
    以上仅是初学者一点思考,供大家一哂~~~
  • 相关阅读:
    HTTP协议简介
    Web开发中B/S架构和C/S架构的区别
    软件测试作业三
    Java8 时间处理
    Java EE
    Java 中的 I/O 抽象
    Python 高级 I/O 多路复用
    SQL 与关系代数
    Python 协程与事件循环
    Java SE 5.0
  • 原文地址:https://www.cnblogs.com/mingzhang/p/11001809.html
Copyright © 2011-2022 走看看