Home > Backend Development > C++ > Why Do Non-Const Member Functions Cause Errors When Used with Const Objects in a `std::set`?

Why Do Non-Const Member Functions Cause Errors When Used with Const Objects in a `std::set`?

Patricia Arquette
Release: 2024-12-15 12:56:30
Original
752 people have browsed it

Why Do Non-Const Member Functions Cause Errors When Used with Const Objects in a `std::set`?

Error in Passing Non-Const Member Functions to Const Objects

In the provided code, a std::set is used to store StudentT objects. The issue arises when attempting to call the getId() and getName() member functions on objects within the set. These member functions are not marked as const, which means they may modify the object's data. However, the objects in the std::set are stored as const StudentT, preventing any modifications.

The compiler detects this inconsistency and generates the following error messages:

../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
Copy after login

This error indicates that the compiler is attempting to pass a const object as the this argument to non-const member functions, which is prohibited.

Solution:

To resolve this issue, modify the getId() and getName() member functions to be const as follows:

int getId() const {
    return id;
}

string getName() const {
    return name;
}
Copy after login

By marking these functions as const, you ensure that they will not modify the object's data and can be safely called on const objects.

Additionally, it is also recommended to make the < operator comparison function const by passing const references to its parameters:

inline bool operator< (const StudentT &s1, const StudentT &s2) {
    return s1.getId() < s2.getId();
}
Copy after login

These modifications will prevent unexpected errors and ensure that the code operates correctly.

The above is the detailed content of Why Do Non-Const Member Functions Cause Errors When Used with Const Objects in a `std::set`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template