a = "foo";printf(a);a = "123";printf(a);int n = a; // notice str -> int conversiona = 456; // notice int -> str conversionprintf(a);
我已经为string到整数转换分配了operator =()方法.如何声明另一个operator =()以便我可以执行反向方法?
当我宣布另一个时,它似乎覆盖了前一个.
String::operator const char *() { return cpstringBuffer;}String::operator const int() { return atoi(cpstringBuffer);}voID String::operator=(const char* s) { ResizeBuffer(strlen(s)); strcpy(cpstringBuffer,s);}bool String::operator==(const char* s) { return (strcmp(cpstringBuffer,s) != 0);}//voID String::operator=(int n) {// char _cBuffer[33];// char* s = itoa(n,_cBuffer,10);// ResizeBuffer(strlen(_cBuffer));// strcpy(cpstringBuffer,_cBuffer);//}解决方法 单参数构造函数可以充当int-> String转换,而所谓的转换运算符可以反转int-> String
class String{public: String(int) {} // initialization of String with int String& operator=(int) {} // assignment of int to String operator int() const {} // String to int};
但请注意,这些转换会隐式发生,您很容易被咬伤.假设您将扩展此类以接受std :: string参数和转换
class String{public: String(int) {} // int to String String(std::string) {} // std::string to String // plus two assignment operators operator int() const {} // String to int operator std::string const {} // String to std::string};
你会有这两个函数重载
voID fun(int) { // bla }voID fun(std::string) { // bla }
现在尝试调用fun(String()).您会收到编译错误,因为存在多个可靠的隐式转换.这就是为什么C 98允许在单参数构造函数前显式关键字,而C 11将它扩展到显式转换运算符.
所以你会写:
class String{public: explicit String(int) {} // int to String explicit operator int() const {} // String to int };
隐式转换可能合法的一个示例是希望从smart_pointer< Derived>转换为bool或(如果它们是模板化的)智能指针类.到smart_pointer< Base>.
总结以上是内存溢出为你收集整理的C多个运算符=()全部内容,希望文章能够帮你解决C多个运算符=()所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)