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

c++ emulate typecasting using assignment operator

这是我的class --

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 ;
        }
};

这是我的主要 --

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 ;

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

error: conversion from ‘const char [4]’ to non-scalar type ‘stuff’ requested

但我实际上想做的是通过说 stuff s5 = "bcd" 来模仿语句 stuff s5("bcd")

如何实现这样的编码结构?

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

stuff(const char* s) : stuff {std::string{s}} {}

您需要一个采用 const char * 的转换构造函数。在 C++11 或更高版本中,这可以委托给现有的 string 构造函数:

stuff(const char * s) : stuff(std::string(s)) {}

历史上,或者如果你想避免创建一个临时字符串,它可能是最简单的

stuff(const char * s) {
    this->s_val = s[0];
    this->e_val = s[std::strlen(s)-1];
}

(遵循构造函数体中的赋值约定,而不是直接初始化。)

否则,将不允许从字符串文字进行隐式转换,因为它需要两次用户定义的转换(const char *std::stringstuff),但是隐式转换序列只能涉及一个。显式转换(如 stuff s5("bcd");)可以通过 string 构造函数完成。

您还可以删除复制构造函数和复制赋值运算符:它们的作用与隐式生成的完全相同。