当我遇到以下示例时,我正在读一本关于c ++的书:
#include <iostream>
#include <string>
using namespace std;
int main () {
const char *message = "how do you do\n";
string s(message);
cout << s << " and its size:" << s.size() << endl;
}
Run Code Online (Sandbox Code Playgroud)
我想知道它到底做了什么.我们如何在s(消息)中传递变量inte另一个变量?提前致谢
s(message)实际上调用 的构造函数std::string,该构造函数根据 指向的给定字符数组构造该类型的新对象message。s只是赋予字符串对象的任意名称。std::string是 C++ 处理字符串的惯用对象,它通常优于原始 C 字符串。
考虑这个简单的示例:
// Declare a fresh class
class A {
public:
// a (default) constructor that takes no parameters and sets storedValue to 0.
A() {storedValue=0;}
// and a constructor taking an integer
A(int someValue) {storedValue=someValue;}
// and a public integer member
public:
int storedValue;
};
// now create instances of this class:
A a(5);
// or
A a = A(5);
// or even
A a = 5;
// in all cases, the constructor A::A(int) is called.
// in all three cases, a.storedValue would be 5
// now, the default constructor (with no arguments) is called, thus
// a.storedValue is 0.
A a;
// same here
A a = A();
Run Code Online (Sandbox Code Playgroud)
std::string声明各种构造函数,包括接受 aconst char*进行初始化的构造函数 - 编译器根据参数的类型和数量自动选择正确的构造函数,因此在您的情况下string::string(const char*)会选择。