C++ 访问冲突,无法找出原因

C++ 访问冲突,无法找出原因,c++,C++,因此,我们一直在构建这个类: public class BitArray { public: unsigned char* Data; UInt64 BitLen; UInt64 ByteLen; private: void SetLen(UInt64 BitLen) { this->BitLen = BitLen; ByteLen = (BitLen + 7) / 8; Data = new unsigne

因此,我们一直在构建这个类:

public class BitArray {
public:
    unsigned char* Data;
    UInt64 BitLen;
    UInt64 ByteLen;

private:
    void SetLen(UInt64 BitLen) {
        this->BitLen = BitLen;
        ByteLen = (BitLen + 7) / 8;
        Data = new unsigned char(ByteLen + 1);
        Data[ByteLen] = 0;
    }

public:
    BitArray(UInt64 BitLen) {
        SetLen(BitLen);
    }

    BitArray(unsigned char* Data, UInt64 BitLen) {
        SetLen(BitLen);
        memcpy(this->Data, Data, ByteLen);
    }

    unsigned char GetByte(UInt64 BitStart) {
        UInt64 ByteStart = BitStart / 8;
        unsigned char BitsLow = (BitStart - ByteStart * 8);
        unsigned char BitsHigh = 8 - BitsLow;

        unsigned char high = (Data[ByteStart] & ((1 << BitsHigh) - 1)) << BitsLow;  
        unsigned char low = (Data[ByteStart + 1] >> BitsHigh) & ((1 << BitsLow) - 1);

        return high | low;
    }

    BitArray* SubArray(UInt64 BitStart, UInt64 BitLen) {
        BitArray* ret = new BitArray(BitLen);
        UInt64 rc = 0;

        for (UInt64 i = BitStart; i < BitLen; i += 8) {
            ret->Data[rc] = GetByte(i);
            rc++;
        }

        Data[rc - 1] ^= (1 << (BitLen - ret->ByteLen * 8)) - 1;

        return ret;
    }

};

您可能想考虑创建一个字符数组,更改:

Data = new unsigned char(ByteLen + 1);
进入:

在前者中,括号内的值不是所需的长度,而是
*Data
初始化为的值。如果使用65(在ASCII系统中),第一个字符将变成
A


已经说过,C++已经有了一个非常有效的<代码> STD::BITSET ,用于你所处的情况。如果你的目的是学习如何制作课程,那么一定要写你自己的。但是,如果你想让你的生活简单,你可能想考虑使用已经提供的设施而不是滚动你自己的设备。< /P>你调试了吗?您如何调用子阵列?所有变量的值是什么?你应该能够在纸上解决这个问题。调试它吗?当我在调试模式下点击runin VS时,我得到的只是访问冲突错误。

公共类
?这是一个VC++扩展吗?还有,main()看起来怎么样?请提供一个实例,以便我们可以重现该问题。@user81993:是的,调试它。你知道,用你的调试器。因此,您可以单步执行代码,设置断点,分析所有变量的值,并找出有关访问冲突的详细信息。使用
std::vector
会更好。这段代码非常脆弱。矢量有什么帮助?(还有,这个类还没完成)@user81993:它会修复你的内存泄漏,而不必麻烦你去弄对。
Data = new unsigned char(ByteLen + 1);
Data = new unsigned char[ByteLen + 1];