【问题标题】:Not able to insert class object inside set in C++?无法在 C++ 中的集合中插入类对象?
【发布时间】:2016-04-17 19:21:26
【问题描述】:

编译器显示错误提示 23:18:错误:将 'const A' 作为 'void A::show()' 的 'this' 参数传递会丢弃限定符 [-fpermissive] 想知道我在这个程序中在哪里使用 const

#include <iostream>
#include <memory>
#include <string>
#include <set>
using namespace std;
class A
{
    int i;
    public:
    A(int pi):i(pi) {}
    void show() { cout<<i<<endl; }
    ~A() { cout<<"Destructor : "<<i<<endl; }
};
int main()
{
   set <A> s;

   s.emplace(A(40));
   s.emplace(A(10));
   s.emplace(A(30));
   s.emplace(A(20));
   set <A>::iterator it;
   for(it = s.begin(); it != s.end() ; it++)      // Line 23
      (*it).show();
   return 0;
}

我得到了上面代码的答案,但是为什么在指针的情况下它工作正常。例如

#include <iostream>
#include <memory>
#include <string>
#include <set>
using namespace std;
class A
{
    int i;
    public:
    A(int pi):i(pi) {}
    void show() { cout<<i<<endl; }
    ~A() { cout<<"Destructor : "<<i<<endl; }
};
int main()
{
   set <A *> s;
   s.emplace(new A(40));
   s.emplace(new A(10));
   s.emplace(new A(30));
   s.emplace(new A(20));
   set <A *>::iterator it;
   for(it = s.begin(); it != s.end() ; it++)
      (*it)->show();
   return 0;
}

输出: 40 10 30 20 我知道在这种情况下我还需要定义自己的删除器。只是在考虑如何做到这一点?

【问题讨论】:

  • 您在此程序中使用const 的位置:look here。因为 show 不是 const 所以你的错误。由于 C++11 std::set::iteratorconst 双向的。将show 设为const,它应该可以工作。
  • 老实说,我对您如何设法将 A 类类型存储在一个没有比较器的集合中印象深刻。迟早你也得照顾好它。
  • 好吧,我检查了两种迭代器 const 和 non const 都在那里。但是是的,在使函数 show const 和是的 Comparator 函数之后,它工作正常。但是,如果我插入相同类类型的指针对象,它工作正常并且没有显示错误,也不需要比较器函数,但是不是基于 int 元素 i 存储指针对象,而是按照元素插入的顺序。你能解释一下为什么会这样吗?
  • 和指针一起工作,因为这里指针是const,show()不会修改指针。
  • 请阅读tour。并考虑接受对您有帮助的答案。

标签: c++ set


【解决方案1】:

一个集合包含一组排序的独特对象。要对对象进行排序,需要一个比较器,如下所示:

bool operator<(const A& lhs, const A& rhs) {
    return lhs.i < rhs.i; // assuming 'i' is public
}

我在您的代码中看不到任何比较器,您确定可以将“A”类对象插入集合中吗?

要修复“第 23 行”错误,只需将方法 show() 标记为 const,因为 const 中的迭代器:

void show() const { cout << i << endl; }

另一种解决方法是const_cast,但这是不好的做法:

const_cast<A&>(*it).show();

请注意,const 在这种情况下非常有意义。否则,您可能会更改已排序的对象(例如:更改值i)。这可能会破坏排序顺序。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
相关资源
最近更新 更多