将一个int(例如10)分配给c ++中结构中的字符串成员,为什么编译成功?

assign an int(eg. 10) to a string member in a struct in c++, why it compile success?

我正在为第 5 章,ex01 练习 : 编写一个名为 Lib 的结构,其中包含三个字符串对象 a、b 和 c。 在 main( ) 中创建一个名为 x 的 Lib 对象并分配给 x.a、x.b 和 x.c。 打印出值。

一开始,我正在尝试:

// ex02.cpp
#include <iostream>
#include <string>
using namespace std;

struct Lib {
    string a;
    string b;
    string c;
};

int main(){
    Lib x;
    x.a = 1;    // here I forgot the string object, and incorrectly assign the wrong value to x.a
    x.b = 2;
    x.c = 3;
    cout << x.a << " " << x.b << " " << x.c << endl;
    return 0;
}

可以编译成功,但是运行结果好像只有两个空格:

[root@VM-0-2-centos ch05]# g++ ex02.cpp 
[root@VM-0-2-centos ch05]# ./a.out 
  
[root@VM-0-2-centos ch05]# 

这时候发现赋值错误。但为什么它不应该给出编译错误? 当我将作业修改为以下内容时:

    x.a = "hello";     
    x.b = "world";
    x.c = "welcome";

编译成功,给出正确的运行结果:

[root@VM-0-2-centos ch05]# g++ ex02.cpp 
[root@VM-0-2-centos ch05]# ./a.out 
hello world welcome
[root@VM-0-2-centos ch05]# 

我的问题是为什么x.a = 1可以编译成功? 当我尝试时:

string test = 1;

编译会报错:

error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]

你需要自己验证我的说法。查看字符串代码。 首先,当你声明 Lib x 时,x (a, b, c) 的成员将调用字符串构造函数。所以给x(x.a = 1)的成员赋值时,会调用“=operation”。

但是,string test = 1,它会调用构造函数。

最大的不同是来电者。字符串构造函数的参数类型是“const char*”,但是“=operation”可以得到其他类型的参数。所以, x.a = 1 at compile 通过了。 注意,默认情况下,“int”将转换为特定类型。

谢谢,@Muqali He,你给了我提示和方向。 我尝试从这里理解字符串 class:https://www.cplusplus.com/reference/string/string/operator=/ 我明白了一点。 对于c++98,当我使用“=”时,有三个重载成员函数:

当我尝试时:

string t2;
t2 = "test";

没关系。我尝试:

string t3;
t3 = 256;

它会收到警告:

warning: overflow in implicit constant conversion

此时256会被识别为char。当你输出这个值时,它会转换成它的ASCII码:

string t4;
t4 = 100;
cout << "t4= " << t4 << endl;

输出是

t4 = d

如果我尝试:

string t5 = 100;    // it will compile error

因为没有对应的构造函数