我试图让一个允许隐式转换为某些内置类型的类,比如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; }
但是这个:
#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; }
在Visual Studio 2010中给出了这个错误:错误C2511:’CustomizedInt :: operator unsigned long(void)’:’CustomizedInt’中找不到重载的成员函数
现在,如果我从运算符定义中删除关键字const,一切正常.这是一个错误吗?我读到我应该在每个(公共)方法/运算符之后使用const关键字,以便清楚地声明它不会以任何方式改变当前对象.
此外,我知道定义这样的运算符可能是不好的做法,但我不确定我是否完全理解相关的警告.有人可以概述一下吗?仅仅定义一个名为ToUnsignedLongInt的公共方法会更好吗?