简体   繁体   English

如何将指针 class 设置为 int 值以传递给 function? 如何将class的成员设置为ByteWord中的前8位值?

[英]How to set pointer class to int value to pass into a function? How to set member of class to the first 8-bits of value in ByteWord?

I created 2 complex types BitsByte variable pointers and initially set them to nullptr.我创建了 2 个复杂类型的 BitsByte 变量指针,并最初将它们设置为 nullptr。 One will hold the uppers Byte of the word and the other will hold the lower Byte of the Word.一个保存字的高位字节,另一个保存字的低位字节。

// File: BitsWord.h
class BitsWord
{
private:
int value;
int bits[16] = {};

    BitsByte* mLower{nullptr};
    BitsByte* mUpper{nullptr}; ...

I have a setValue function to set mUpper and mLower to the first two bytes of value that will convert the decimal number into the binary equivalent in an array named bits.我有一个 setValue function 将 mUpper 和 mLower 设置为值的前两个字节,这会将十进制数转换为名为 bits 的数组中的等效二进制数。

// BitsWord.cpp
void BitsWord::setValue(int value)
{ 
for(int i = 0; i < 16; i++)
    { bits[i] = static_cast<bool>(value & (1 << i)); }
reverse(begin(bits), end(bits));
}

I want to call the setValue function on mLower passing value.我想在 mLower 通过值上调用 setValue function。 Debugger shows Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) on Xcode when I'm attempting to set mLower to the first 8-bits of value.当我尝试将 mLower 设置为值的前 8 位时,调试器显示 Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) on Xcode。

*mLower = value;     setValue(value);

You need to allocate memory to mLower before this line:您需要在此行之前将 memory 分配给 mLower:

*mLower = value;

You should first create an instance of BitsByte, then assign the pointer mLower to point to that instance before calling setValue() function.您应该首先创建一个 BitsByte 实例,然后在调用 setValue() function 之前分配指针 mLower 以指向该实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM