错误:通过xxx作为xxx的'this'参数抛弃限定符 [英] error: passing xxx as 'this' argument of xxx discards qualifiers
问题描述
#include <iostream>
#include <set>
using namespace std;
class StudentT {
public:
int id;
string name;
public:
StudentT(int _id, string _name) : id(_id), name(_name) {
}
int getId() {
return id;
}
string getName() {
return name;
}
};
inline bool operator< (StudentT s1, StudentT s2) {
return s1.getId() < s2.getId();
}
int main() {
set<StudentT> st;
StudentT s1(0, "Tom");
StudentT s2(1, "Tim");
st.insert(s1);
st.insert(s2);
set<StudentT> :: iterator itr;
for (itr = st.begin(); itr != st.end(); itr++) {
cout << itr->getId() << " " << itr->getName() << endl;
}
return 0;
}
行内:
cout << itr->getId() << " " << itr->getName() << endl;
它给出一个错误:
../ main.cpp:35:错误:将'Student StudentT'作为'int StudentT :: getId()'的'this'参数丢弃限定符
../main.cpp:35: error: passing 'const StudentT' as 'this' argument of 'int StudentT::getId()' discards qualifiers
../ main.cpp:35:error:传递'const StudentT'作为'std :: string的参数'StudentT :: getName()'丢弃限定符
../main.cpp:35: error: passing 'const StudentT' as 'this' argument of 'std::string StudentT::getName()' discards qualifiers
此代码有什么问题?谢谢!
What's wrong with this code? Thank you!
推荐答案
std :: set
存储为 const StudentT
。因此,当您尝试使用 const
对象调用 getId()
时,编译器会检测到一个问题,在const对象上的一个非const成员函数是不允许的,因为非const成员函数使NO PROMISE不修改对象;因此编译器会做一个安全假设, getId()
可能会尝试修改对象,但同时,它也注意到对象是const;所以任何尝试修改const对象应该是一个错误。因此编译器生成错误消息。
The objects in the std::set
are stored as const StudentT
. So when you try to call getId()
with the const
object the compiler detects a problem, namely you're calling a non-const member function on const object which is not allowed because non-const member functions make NO PROMISE not to modify the object; so the compiler is going to make a safe assumption that getId()
might attempt to modify the object but at the same time, it also notices that the object is const; so any attempt to modify the const object should be an error. Hence compiler generates error message.
解决方案很简单:将函数const作为:
The solution is simple: make the functions const as:
int getId() const {
return id;
}
string getName() const {
return name;
}
这是必要的,因为现在你可以调用 getId )
和 getName()
在const对象上:
This is necessary because now you can call getId()
and getName()
on const objects as:
void f(const StudentT & s)
{
cout << s.getId(); //now okay, but error with your versions
cout << s.getName(); //now okay, but error with your versions
}
实现运算符<
as:
inline bool operator< (const StudentT & s1, const StudentT & s2)
{
return s1.getId() < s2.getId();
}
注意参数现在为 const
参考。
这篇关于错误:通过xxx作为xxx的'this'参数抛弃限定符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!