gpt4 book ai didi

c++ - C++中的字符串对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:08:46 25 4
gpt4 key购买 nike

当我遇到下面的例子时,我正在看一本关于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;
}

我想知道它到底做了什么。我们如何像在 s(message) 中那样将一个变量传递给另一个变量?提前致谢

最佳答案

s(message)实际上调用了std::string的构造函数,它根据指向的给定字符数组构造了一个新的该类型的对象消息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();

std::string 声明各种构造函数,包括接受 const char* 进行初始化的构造函数 - 编译器会根据类型和数量自动选择正确的构造函数参数,因此在您的情况下选择了 string::string(const char*)

关于c++ - C++中的字符串对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5355685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com