加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C多个运算符=()

发布时间:2020-12-16 10:22:41 所属栏目:百科 来源:网络整理
导读:我正在写一个String类.我希望能够分配我的字符串,如; a = "foo";printf(a);a = "123";printf(a);int n = a; // notice str - int conversiona = 456; // notice int - str conversionprintf(a); 我已经为string到整数转换分配了operator =()方法.如何声明另
我正在写一个String类.我希望能够分配我的字符串,如;

a = "foo";
printf(a);
a = "123";
printf(a);
int n = a; // notice str -> int conversion
a = 456; // notice int -> str conversion
printf(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>.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读