一句话经验:sizeof是操作符而不是函数

本文详细解释了C/C++中sizeof操作符的功能与用法。它返回变量或类型的存储大小(以字节为单位),适用于变量、类型乃至静态数组。文中还提到了sizeof不能用于动态分配数组或外部数组。

sizeof (int) 说明 sizeof 不是一个函数,函数不接受int做为形参。

MSDN的说明如下:

The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types). This keyword returns a value of type size_t.

The expression is either an identifier or a type-cast expression (a type specifier enclosed in parentheses).

When applied to a structure type or variable, sizeof returns the actual size, which may include padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof returns the size of the entire array. The sizeof operator cannot return the size of dynamically allocated arrays or external arrays.

### 如何在C++中将字符串赋值给变量 在C++中,`std::string` 是种常用的类模板实例化类型,用于处理字符序列。可以通过多种方式将字符串赋值给 `std::string` 类型的变量。 #### 使用构造函数初始化 可以直接通过构造函数来创建并初始化个 `std::string` 对象: ```cpp #include <iostream> #include <string> int main() { std::string str1("Hello, world!"); // 使用字面量初始化 std::cout << str1 << std::endl; const char* cstr = "Another string"; std::string str2(cstr); // 使用 C 风格字符串初始化 std::cout << str2 << std::endl; return 0; } ``` 上述代码展示了两种常见的初始化方法:是直接使用双引号括起来的字符串字面量;二是利用已有的 C 风格字符串(即以 `\0` 结尾的字符数组)。[^1] #### 赋值操作符 (`=`) 除了初始化之外,还可以使用赋值操作符个现有的字符串赋值给另个 `std::string` 变量: ```cpp #include <iostream> #include <string> int main() { std::string originalStr = "Original String"; std::string newStr; newStr = originalStr; // 使用赋值操作符复制内容 std::cout << "Copied String: " << newStr << std::endl; return 0; } ``` 这里需要注意的是,当执行这样的赋值时,实际上是进行了深拷贝(deep copy),这意味着两个对象各自拥有独立的数据副本。如果希望共享数据而不是复制,则可以考虑其他技术如引用或指针。[^3] #### 使用成员函数 `.assign()` 另外,也可以调用 `std::string` 提供的个非常灵活的方法——`.assign()` 来完成这目的: ```cpp #include <iostream> #include <string> int main() { std::string myString; myString.assign("This is an assigned value."); // 字符串字面量分配 std::cout << "Assigned Value: " << myString << std::endl; const char anotherArray[] = {'A', 'B', 'C'}; myString.assign(anotherArray, sizeof(anotherArray)-1); // 数组分配 std::cout << "From Array: " << myString << std::endl; return 0; } ``` 此方法支持多种形式参数输入,比如指定长度子串、范围区间等复杂情况下的重新定义行为。[^2] 综上所述,在实际编程过程中可以根据具体需求选用不同的手段实现字符串向变量的传递过程。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值