When encountering the error "passing const xxx as 'this' argument of member function discards qualifiers," it indicates that a non-const member function is being called on a const object. In this case, the issue arises when accessing getId() and getName() methods of StudentT objects stored within a std::set.
The objects in the std::set are stored as const StudentT. When calling getId() and getName() on the iterator dereference (*itr), the compiler detects a mismatch. The member functions are non-const, but the object being accessed is const.
To resolve this issue, the member functions getId() and getName() should be declared as const methods:
int getId() const { return id; } string getName() const { return name; }
By declaring them as const methods, it guarantees that they will not modify the StudentT object, making it safe to call them on const objects.
The operator< should also be declared as a const method, as it is called on const StudentT objects when performing set operations:
inline bool operator< (const StudentT & s1, const StudentT & s2) { return s1.getId() < s2.getId(); }
By declaring it as const, it ensures that the operator does not modify the objects being compared.
The above is the detailed content of How to Fix 'passing const xxx as 'this' argument of member function discards qualifiers' Error in C ?. For more information, please follow other related articles on the PHP Chinese website!