c ++使用赋值运算符模拟类型转换

ram*_*rur 0 c++ constructor operator-overloading c++11

这是我的班级 -

class stuff
{
    private:
        char s_val = 'x';
        char e_val = 'y';
    public:
        stuff() {;}

        stuff(const string &s) {
            this->s_val = s[0];
            this->e_val = s[s.length() - 1];
        }

        stuff(const stuff &other) {
            this->s_val = other.s_val ;
            this->e_val = other.e_val ;
        }

        stuff& operator=(const stuff &other)
        {
            this->s_val = other.s_val;
            this->e_val = other.e_val;
            return *this;
        }

        stuff& operator=(const string &s)
        {
            *this = stuff(s);
            return *this ;
        }

        stuff& operator=(const char *c)
        {
            string s(c);
            *this = stuff(s);
            return *this ;
        }

        friend ostream& operator<<(ostream &os, const stuff &s)
        {
            os << s.s_val << " " << s.e_val ;
            return os ;
        }
};
Run Code Online (Sandbox Code Playgroud)

这是我的主要 -

stuff s1("abc");
cout << s1 << endl ;
stuff s2(s1);
cout << s2 << endl ;
stuff s3 = s2 ;
cout << s3 << endl ;
stuff s4; s4 = "def" ;
cout << s4 << endl ;
// stuff s5 = "def" ; // compiler does not like it
// cout << s5 << endl ;
Run Code Online (Sandbox Code Playgroud)

所以当我说stuff s5 = "def"编译器决定我试图在string和之间进行某种类型转换时stuff,它说 -

error: conversion from ‘const char [4]’ to non-scalar type ‘stuff’ requested
Run Code Online (Sandbox Code Playgroud)

但我实际上要做的是模仿声明stuff s5("bcd")stuff s5 = "bcd".

我如何实现这种编码结构?

Tar*_*ama 5

这将无法编译,因为您的隐式构造函数采用的是const std::string&而不是const char*.const char*是可转换为const std::string,但编译器将只执行一次隐式转换以尝试并实现您的构造函数.你可以通过添加一个构造函数来解决这个问题,该构造函数接受一个const char*和委托给字符串构造函数(需要C++ 11):

stuff(const char* s) : stuff {std::string{s}} {}
Run Code Online (Sandbox Code Playgroud)