【问题标题】:this discards qualifiers what does it mean?这丢弃了限定符是什么意思?
【发布时间】:2020-11-04 08:06:15
【问题描述】:

“this discards qualifiers”,是什么意思?

#include <iostream>
using namespace std;
 #include <iostream>
using namespace std;
class b
{
    public:
    
    void show( b &ob)
    {
        //this =ob;
        cout<<"show";
    }
    
};
int main() 
{
 
  b const ob;
  b ob1;
  ob.show(ob1);
    // your code goes here 
    return 0;
}
   
prog.cpp: In function ‘int main()’:
prog.cpp:23:14: error: passing ‘const b’ as ‘this’ argument discards qualifiers [-fpermissive]
   ob.show(ob1);
              ^

【问题讨论】:

  • 您正试图在 const qualifoed 对象上调用非 const 函数 (b)
  • @sumitkumar 太棒了!请考虑accepting我的回答。您的问题仍列为未回答。
  • @Ann Zen,当然但是我仍在等待最佳答案。暂时,我已经对答案投了赞成票。

标签: c++


【解决方案1】:

在这里,您已将 ob 声明为 const 对象:

b const ob;

但是这里你调用了一个成员函数 (show),它没有标记为const

ob.show(ob1);

将不改变对象(*this)的成员函数标记为const

void show( b &ob) const // <- like this
    {
        //this =ob;
        cout<<"show";
    }

在这种特殊情况下,我还建议您更改show,使其不带任何参数,只显示*this 的内容:

#include <iostream>

class b
{
private:
    int example_of_a_member_variable;

public:
    // example of a converting constructor
    explicit b(int value) : example_of_a_member_variable(value) {}
   
    void show() const
    {
        std::cout << example_of_a_member_variable << '\n';
    }
};

int main() {
    b const ob(1234);
    ob.show();           // prints 1234
}

【讨论】:

  • 嗯,我打算关闭这个,但它比我能找到的任何目标都更好:)
  • @cigien 谢谢!也许我应该做的工作是找到骗子并在那里回答……我不擅长寻找骗子,经常只是开始打字:-)
  • 我明白,写答案通常更快。老实说,改善老骗子的动机也不是很好:(但如果你确实想为thisthis添加答案,那就太好了。这两个问题的答案都不是太令人兴奋:p
猜你喜欢
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 1970-01-01
  • 2012-04-03
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
相关资源
最近更新 更多