Home >Backend Development >C++ >Why Do I Get 'passing 'const StudentT' as 'this' argument' Errors When Accessing Member Functions from a `std::set`?
Inconsistent Function Qualification in Member Function Invocation
In the provided code, the error arises when accessing member functions getId() and getName() from objects stored in the set
To understand this, we need to remember that objects in a set are stored as const references. However, the member functions getId and getName are not declared as const, which implies that they can modify the state of the object.
In the line where the error occurs:
cout << itr->getId() << " " << itr->getName() << endl;
the compiler detects that the itr iterator points to a const StudentT object, which by definition cannot be modified. Consequently, attempting to call non-const member functions on a const object is not allowed, hence the error messages generated:
../main.cpp:35: error: passing 'const StudentT' as 'this' argument of 'int StudentT::getId()' discards qualifiers ../main.cpp:35: error: passing 'const StudentT' as 'this' argument of 'std::string StudentT::getName()' discards qualifiers
To resolve this issue, we must declare the member functions getId and getName as const, indicating that they do not modify the object's state:
int getId() const { return id; } string getName() const { return name; }
By making these functions const, we guarantee that they can be safely invoked on const objects, eliminating the constness mismatch error.
Additionally, the operator< overload for the StudentT class should also be declared as const:
inline bool operator<(const StudentT &s1, const StudentT &s2) { return s1.getId() < s2.getId(); }
This ensures that the comparison operation does not attempt to modify the objects being compared, maintaining code correctness.
The above is the detailed content of Why Do I Get 'passing 'const StudentT' as 'this' argument' Errors When Accessing Member Functions from a `std::set`?. For more information, please follow other related articles on the PHP Chinese website!