Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

c++ - Initializing a string with a single character in CPP

I want to initialize a string with a single character. The following code doesn't work:

int main()
{
    string s = 'c';
    cout<<s;
    return 0;
}

// Result:
error: conversion from ‘char’ to non-scalar type ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ requested
  string s = 'c';

But the following does. Why is it so?

int main()
{
    string s;
    s = 'c';
    cout<<s;
    return 0;
}
// Output: c[Finished in 0.8s]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you do

string s = 'c';

you are basically invoking constructor initialisation rather than an assignment operation. But there isn’t any constructor for std::string that takes only a single char as input. There is however one std::string(n, c), where n is the number of characters c in the string.

When you do

s = 'c'

you do an assignment operation, invoking the overloaded string::operator= (string& operator= (char c);) for std::string. Now this method is overloaded to accept a single char as input as well, as you can see from the code snippet at this reference as well as at this one.

std::string str1;
// ...
// (4) operator=( CharT );
str1 = '!'; 

Additionally, std::string::assign doesn’t accept a single char, similar to the constructor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...