gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:02:12 25 4
gpt4 key购买 nike

这是我的课--

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* 并委托(delegate)给字符串构造函数(需要 C++11):

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

关于c++使用赋值运算符模拟类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30344762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com