Files
XCSDD/docs/api/containers/string/operator-assign.md

48 lines
1.1 KiB
Markdown
Raw Normal View History

# String::operator=
```cpp
String& operator=(const String& other);
String& operator=(String&& other) noexcept;
String& operator=(const char* str);
```
将新的值赋给 String 对象,替换原有的内容。
**参数:**
- `other` - 另一个 String 对象(拷贝赋值或移动赋值)
- `str` - 以 null 结尾的 C 字符串
**返回:** `*this`,支持链式调用
**复杂度:**
- 拷贝赋值O(n)n 为 other 的长度
- 移动赋值O(1)
-`const char*` 赋值O(n)n 为 str 的长度
**示例:**
```cpp
#include "XCEngine/Containers/String.h"
#include <iostream>
int main() {
XCEngine::Containers::String s1;
XCEngine::Containers::String s2("hello");
s1 = s2; // 拷贝赋值
std::cout << s1.CStr() << std::endl; // 输出: hello
s1 = "world"; // 从 const char* 赋值
std::cout << s1.CStr() << std::endl; // 输出: world
XCEngine::Containers::String s3("moved");
s1 = std::move(s3); // 移动赋值
std::cout << s1.CStr() << std::endl; // 输出: moved
return 0;
}
```
## 相关文档
- [String 总览](string.md) - 返回类总览