Mih*_*dor 7 c++ operator-overloading const-correctness
我试图有一个允许隐式转换为某些内置类型的类,比如unsigned long int,因为我试图尽可能正确地做这个(这是我在C++中的第一个重要项目),我遇到了一个奇怪的关于const正确性的问题:
这有效:
#include <iostream>
class CustomizedInt
{
private:
int data;
public:
CustomizedInt();
CustomizedInt(int input);
operator unsigned long int () const
{
unsigned long int output;
output = (unsigned long int)data;
return output;
}
};
CustomizedInt::CustomizedInt()
{
this->data = 0;
}
CustomizedInt::CustomizedInt(int input)
{
this->data = input;
}
int main()
{
CustomizedInt x;
unsigned long int y = x;
std::cout << y << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是这个:
#include <iostream>
class CustomizedInt
{
private:
int data;
public:
CustomizedInt();
CustomizedInt(int input);
operator unsigned long int () const;
};
CustomizedInt::CustomizedInt()
{
this->data = 0;
}
CustomizedInt::CustomizedInt(int input)
{
this->data = input;
}
CustomizedInt::operator unsigned long()
{
unsigned long int output;
output = (unsigned long int)data;
return output;
}
int main()
{
CustomizedInt x;
unsigned long int y = x;
std::cout << y << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在Visual Studio 2010中给我这个错误: error C2511: 'CustomizedInt::operator unsigned long(void)' : overloaded member function not found in 'CustomizedInt'
现在,如果我从运算符定义中删除关键字const,一切正常.这是一个错误吗?我读到我应该在每个(公共)方法/运算符之后使用const关键字,以便清楚地声明它不会以任何方式改变当前对象.
此外,我知道定义这样的运算符可能是不好的做法,但我不确定我是否完全理解相关的警告.有人可以概述一下吗?仅仅定义一个名为ToUnsignedLongInt的公共方法会更好吗?
函数签名与函数定义不匹配.
operator unsigned long int () const;
Run Code Online (Sandbox Code Playgroud)
和
CustomizedInt::operator unsigned long() { ... }
^^^
const missing
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您应该将转换运算符标记为const因为它不会影响对象的内部状态.
此外,使用构造函数初始化列表初始化成员变量.
CustomizedInt::CustomizedInt()
: data()
{
}
CustomizedInt::CustomizedInt(int input)
: data(input)
{
}
Run Code Online (Sandbox Code Playgroud)
您可以const从声明中删除它,但您几乎肯定想要做的是将其添加到定义中:
CustomizedInt::operator unsigned long() const
{
unsigned long int output;
output = (unsigned long int)data;
return output;
}
Run Code Online (Sandbox Code Playgroud)