首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >运算符const char* ()和显式复制ctor

运算符const char* ()和显式复制ctor
EN

Stack Overflow用户
提问于 2021-01-25 13:31:28
回答 1查看 83关注 0票数 1

因此,我在过去的一次测试中沿着这个问题从我的大学,我注意到一些奇怪的东西,我找不到解释。

问题是:cout << s2;中的main行会打印什么?

我在VS2019调试器中执行了流,并在执行行MyString s2 = s1;时调用了

operator const char* ()const { return str; }

我不知道它为什么会去那里。在此之后,将在s2上调用ctor。

我理解为什么这个实例不会调用复制器,因为它是explicit,为了调用它,行应该是MyString s2(s1);

主要:

代码语言:javascript
复制
 int main()
 {
    MyString s1;
    cout << s1;
    MyString s2 = s1;
    cout << s2;
    return 1;
}

守则:

代码语言:javascript
复制
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

 class MyString
 {
     class MyChar
    {
         MyString * pStr;
         int index;
    public:
         MyChar(MyString * p, int i) : pStr(p), index(i) {}
         const MyChar & operator=(char c) {
             pStr->set(index, c); // call copy-on-write
             return *this;
            }
         operator char()const { return pStr->str[index]; }
    };

    friend class MyChar;
    char* str;
    int* ref_counter;
    void attach(const MyString & s) {
        ref_counter = s.ref_counter;
        str = s.str;
        ++(*ref_counter);
    }
    void detach() {
        if (--(*ref_counter) == 0) {
            delete[]str;
            delete ref_counter;
            
        }   
    }
    void set(int index, char c) {
        // this is the copy-on-write
        MyString temp(str);
        detach();
        attach(temp);
        str[index] = c;
    }
public:
    MyString(const char* s = "") : ref_counter(new int(1))
    {
         str = new char[strlen(s) + 1];
         strcpy(str, s);
    }
    explicit MyString(const MyString& s) { attach(s); } 
    ~MyString() { detach(); }
    const MyString & operator=(const MyString & s)
        {detach(); attach(s); return *this; }
    operator const char* ()const { return str; }        //operation in question
    MyChar operator[](int index) {
        return MyChar(this, index);
    }
    char operator[](int index)const {
        return str[index];
    }
    friend ostream & operator<<
        (ostream & out, const MyString & s) {
        return out << s.str << ", ref count = "
            << *s.ref_counter << endl;
    }
};

希望有人能帮我理解这个转变

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-25 13:40:16

编译器试图找到一种编译程序的方法。由于它不能进行隐式复制(explicit复制ctor),所以它尝试其他构造函数,并且在隐式用户定义的转换到const char*之后,const char* 1似乎是一个可行的候选函数。没有其他候选人,所以它被选中了。

有用的附加案文如下:

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65885762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档