gpt4 book ai didi

C++ 字符串成员构造

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:17 26 4
gpt4 key购买 nike

如何为字符串成员使用构造函数?这是一个例子(我意识到这是错误的)

class Filestring {
public:
string sFile;

Filestring(const string &path)
{
ifstream filestream(path.c_str());
// How can I use the constructor for the member sFile??
// I know this is wrong, but this illustrates what I want to do.
string sFile((istreambuf_iterator<char>(filestream)), istreambuf_iterator<char>());
}
};

所以基本上我希望能够在不进行字符串复制的情况下使用成员 sFile 的构造函数。有没有办法通过赋值来实现?

最佳答案

你可以使用的最好的是string::assign:

sFile.assign(istreambuf_iterator<char>(filestream), istreambuf_iterator<char>());

但是在 C++11 中有一个字符串的移动赋值运算符,所以执行以下操作几乎同样有效(没有字符数据的拷贝,字符数据被移动):

sFile = string(istreambuf_iterator<char>(filestream), istreambuf_iterator<char>());

当 C++11 移动分配不可用时,另一个技巧是使用 std::swapstring::swap。效率可能与移动分配变体几乎相同。

string newContent(istreambuf_iterator<char>(filestream), istreambuf_iterator<char>());
std::swap(sFile, newContent); // or sFile.swap(newContent);

关于C++ 字符串成员构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10216954/

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