c++使用赋值操作符模拟类型转换

c++ emulate typecasting using assignment operator

本文关键字:模拟 类型转换 赋值操作符 c++      更新时间:2023-10-16

这是我的类——

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::string再到stuff),但是隐式转换序列只能包含一个。显式转换(如stuff s5("bcd");)可以通过string构造函数完成。

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