C++ 对象具有与成员函数不兼容的类型限定符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20252932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
the object has type qualifiers that are not compatible with the member function
提问by Karedia Noorsil
#include<iostream>
using namespace std;
class PhoneNumber
{
int areacode;
int localnum;
public:
PhoneNumber();
PhoneNumber(const int, const int);
void display() const;
bool valid() const;
void set(int, int);
PhoneNumber& operator=(const PhoneNumber& no);
PhoneNumber(const PhoneNumber&);
};
istream& operator>>(istream& is, const PhoneNumber& no);
istream& operator>>(istream& is, const PhoneNumber& no)
{
int area, local;
cout << "Area Code : ";
is >> area;
cout << "Local number : ";
is >> local;
no.set(area, local);
return is;
}
at no.set(area, local);it says that "the object has type qualifiers that are not compatible with the member function"
在 no.set(area, local); 它说“该对象具有与成员函数不兼容的类型限定符”
what should i do...?
我该怎么办...?
采纳答案by Karedia Noorsil
You're passing no
as const
, but you try to modify it.
您正在传递no
as const
,但您尝试修改它。
istream& operator>>(istream& is, const PhoneNumber& no)
//-------------------------------^
{
int area, local;
cout << "Area Code : ";
is >> area;
cout << "Local number : ";
is >> local;
no.set(area, local); // <------
return is;
}
回答by Luchian Grigore
Your set
method is not const
(nor should it be), but you're attempting to call it on a const
object.
您的set
方法不是const
(也不应该是),但是您试图在const
对象上调用它。
Remove the const
from the parameter to operator >>
:
const
从参数中删除operator >>
:
istream& operator>>(istream& is, PhoneNumber& no)
回答by Vlad from Moscow
In the operator >> there is the second parameter with type const PhoneNumber& no that is it is a constant object, But you are trying to change it using member function set. For const objects you may call only member functions that have qualifier const.
在操作符 >> 中有第二个类型为 const PhoneNumber& no 的参数,它是一个常量对象,但您正试图使用成员函数集来更改它。对于 const 对象,您只能调用具有限定符 const 的成员函数。