Const member function

I have the following code:

class Test{
private:
    int id;
public:
     Test(int v):id(v) {}
     int getId() { return id;};          // however,I change this method signature
                                            int getId() const { return id;};
                                            and all the errors gone
};

 struct compare{
   bool operator()(const Test& t1, const Test& t2){
    return t1.getId() < t2.getId();      // got error here
   }  
 };

 int main(int argc, char *argv[]){
   set<Test, compare> s;
   Test str[] = {Test(1), Test(2), Test(3)};
   for (int i = 0; i < 3; ++i){
     s.insert(str[i]);
   }
   for (set<Test>::iterator it = s.begin(); it != s.end(); ++it){
     cout << it->getId() << "\n";        // got error here
   }    
   return EXIT_SUCCESS;
 }

I got this error when I called the getId () method with this code:

passing `const Test' as `this' argument of `int Test::getId()' discards qualifiers

I don’t know why I need const in the getId () method to fix this error? Thanks

+3
source share
5 answers
bool operator()(const Test& t1, const Test& t2)

Your operator accepts references to objects const Test. You can only call const-qualified member functions through a reference to const-qualified type.

set<Test>::iterator it = s.begin()

The elements of a std::setare immutable: you cannot change them. Because of this, iterators in std::setalways refer to the const-qualified object .

+10
source

set::iterator const , - , (.. , , .. , ). iterator - const.

, const_iterator vs iterator .

+3
const Test& t1

t1 , . , , - const!

? , const ! , const//.
const getId, , .

int getId() const { return id;};

. , std::set, , .

+2

const-- const.

set<Test>::iterator it = s.begin(); 

const, - , const- .

+1

The operator () has const Test&objects in its parameter list, so when you call the const object, your function must be declared using the const specifier.

int getId() const { return id;};

Also change

for (std::set<Test, compare>::const_iterator it = s.begin(); it != s.end(); ++it){
       std::cout << it->getId() << "\n";        // got error here
   }
0
source

All Articles