如何将指针类赋值为int值传函数?提取ByteWord低8位赋值类成员报错
问题分析与解决方案
1. 解决EXC_BAD_ACCESS错误
你遇到的Thread 1: EXC_BAD_ACCESS错误根源是空指针访问:mLower和mUpper被初始化为nullptr,但你没有为它们分配实际的BitsByte对象内存,直接调用mLower->setValue()会访问内存地址0x0,触发崩溃。
修复方式:
在BitsWord的构造函数中为指针分配对象实例:
class BitsWord { private: BitsByte* mLower; BitsByte* mUpper; public: BitsWord() { // 为指针分配实际的BitsByte对象 mLower = new BitsByte(); mUpper = new BitsByte(); } // 析构函数中释放内存,避免泄漏 ~BitsWord() { delete mLower; delete mUpper; } // 禁用拷贝构造和赋值运算符,防止浅拷贝问题 BitsWord(const BitsWord&) = delete; BitsWord& operator=(const BitsWord&) = delete; void setValue(int value); };
如果想更安全地管理内存,推荐使用智能指针(比如std::unique_ptr),无需手动释放:
#include <memory> class BitsWord { private: std::unique_ptr<BitsByte> mLower; std::unique_ptr<BitsByte> mUpper; public: BitsWord() : mLower(std::make_unique<BitsByte>()), mUpper(std::make_unique<BitsByte>()) {} void setValue(int value); };
2. 将int值传入BitsByte指针指向的对象
假设BitsByte的setValue方法接受int类型参数,确保指针指向有效对象后,直接调用方法传入目标值即可:
void BitsWord::setValue(int value) { // 提取低8位和高8位 int lowerByte = value & 0xFF; // 低8位 int upperByte = (value >> 8) & 0xFF; // 高8位(假设int至少16位) // 传入值给BitsByte对象 mLower->setValue(lowerByte); mUpper->setValue(upperByte); }
如果需要让函数接受BitsByte*参数并设置其值,示例如下:
// 函数定义:接受BitsByte指针并设置int值 void setByteValue(BitsByte* bytePtr, int value) { if (bytePtr != nullptr) { // 先检查指针有效性 bytePtr->setValue(value); } } // 调用示例 setByteValue(mLower, lowerByte);
3. 提取BitsWord对应int值的前8位(高字节)并设置给类成员
通过位运算直接从int值中提取高8位:
- 右移8位:
value >> 8,将高8位移到低8位的位置 - 与
0xFF按位与:(value >> 8) & 0xFF,确保只保留低8位(即原int的高8位)
将提取后的值传入mUpper->setValue()即可,代码已在上述setValue方法中体现。
内容的提问来源于stack exchange,提问作者user18102815
相关产品推荐
相关产品推荐

