Implict type conversion between int and string

How to prevent this implicit type conversion between int and std :: string, which is very dangerous. Here is the code.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s="string";
    s = 123456789;  //assign a int value to std::string
    cout << s;
    // your code goes here
    return 0;
}

The above code may be compiled without warning, and the result is clearly not what the encoder is for. Can this be avoided?

Update: 123456789will trigger an overflow warning if the flag is set -Wall. But if I switch to s = 98, there will be no more warnings. but I really want the string to be a string 98, not an ascii character b. How to prevent this?

+4
source share
1 answer

, , , - . . -Wall -Wextra .

. , implicit type conversion.

, , -Wconstant-conversion.

+4

Source: https://habr.com/ru/post/1598173/


All Articles