C++ 是否可以重载赋值运算符以将字符串文字赋值给用户定义的字符串类型?

C++ 是否可以重载赋值运算符以将字符串文字赋值给用户定义的字符串类型?,c++,assignment-operator,C++,Assignment Operator,第一部分是一个web示例 任务: 可以将C++字符串、C字符串或C字符串文字赋值给C++字符串。 示例: string s1 = "original string"; string s2 = "new string"; char s3[20] = "another string"; s1 = s2;//s1 changed to "new string" s1 = s3;//s1 changed to "another string" s1 = "yet another string";

第一部分是一个web示例

任务:

可以将C++字符串、C字符串或C字符串文字赋值给C++字符串。

示例:

string s1 = "original string";
string s2 = "new string";
char s3[20] = "another string";

s1 = s2;//s1 changed to "new string"
s1 = s3;//s1 changed to "another string"
s1 = "yet another string";
   //s1 changed to "yet another string"
   //Once again, this works because.
   //operator overloading.
这是我下面的问题

class my_string{
public:
.
.
my_string& operator=(const my_string&);
.
.
.
};
如果这是唯一的任务 允许操作员过载,那么如何
s1
是否在上述示例中获取了
“另一个字符串”
的值?

如果我正确理解您的问题,那是因为它不是唯一的赋值运算符,还有其他重载定义。这些是针对C++98的,还有一些是针对C++11的

string& operator= (const string& str);
string& operator= (const char* s);
string& operator= (char c);


s1=“还有一个字符串”
使用列表中的第二个运算符,而
s1=s2
使用第一个。

理论上,我们必须提供一个重载赋值运算符,如下所示:

string& operator= (const char* s);
但是我测试了它。没有它没关系

int main()
{
    mystring s = "assss";
    cout << s << endl;
    s = "aaaaaaaaa";
    cout << s << endl;
    system("pause");
    return 0;
}
intmain()
{
mystring s=“assss”;

cout 1.您的标记错误,2.您的
string
对象和字符串文字不都是“string”,在上下文中,你应该小心区分这些。你的问题是什么?你是问如何允许赋值,还是说允许赋值并问为什么?你的类是否有任何构造函数从另一个字符串类型转换为
my_string
?你的问题没有意义。示例上面的e使用的是
std::string
,而不是
my_string
。我从internet上提取了一个示例,其中涉及由文本字符串分配的std::string对象。然后我展示了运算符重载在我的类中的外观。我不明白为什么运算符重载函数只允许作为参数接受相同的类,但std::string能够以不同的方式重载它。