簡體   English   中英

C ++在構造函數中傳遞數組而不在其他地方定義它們

[英]c++ passing arrays in constructor without defining them elsewhere

我目前有以下代碼:

#include "stdafx.h"
#include "AddressInfo.h"

AddressInfo::AddressInfo(int ammoCount, int pointerLevel, DWORD baseAddress, DWORD* offsetArray) {
    ammo = ammoCount;
    numPointers = pointerLevel;
    this->baseAddress = baseAddress;
    offsets = (DWORD*)malloc(sizeof(offsetArray));
    this->offsets = offsetArray;
};

AddressInfo::~AddressInfo() {
    delete[] offsets;
}

void AddressInfo::print() {
    std::cout << this->offsets[0]<< std::endl;
}





DWORD x[] = { 0x374, 0x14, 0x0 };
AddressInfo* ammo = new AddressInfo(1000, 3, (DWORD)(0x00509B74), x);

int main()
{
    ammo->print();
    system("pause");
}

這段代碼有效,但是我想執行以下操作:我不想預先定義數組並將其傳遞給構造函數,而是要按如下所示傳遞數組:{0x374,0x14,0x0}

這可能/這可行嗎

我嘗試過類型轉換:(DWORD *){0x374,0x14,0x0}

您應該將std::vector用於此任務和以后的任務。 看看它使一切變得容易和清潔

#include <iostream>
#include <vector>

class AddressInfo
{
    int ammoCount;
    int pointerLevel;
    std::vector<uint32_t> offsets;

public:
    AddressInfo(int ammoCount, int pointerLevel, std::vector<uint32_t> offsets) :
        ammoCount{ ammoCount }, pointerLevel{ pointerLevel }, offsets{ offsets }
    {   
    }

    void print(size_t i) 
    {
        std::cout << this->offsets.at(i) << std::endl;
    }
};

int main() 
{
    AddressInfo ammo (1000, 0x00509B74, { 0x374, 0x14, 0x0 });
    ammo.print(0);
    ammo.print(1);
    ammo.print(2);

    return 0;
}

https://ideone.com/WaLiP8

這個構造函數是錯誤的

AddressInfo::AddressInfo(
  int ammoCount, 
  int pointerLevel, 
  DWORD baseAddress, 
  DWORD* offsetArray) 
{
  ammo = ammoCount;
  numPointers = pointerLevel;
  this->baseAddress = baseAddress;
  offsets = (DWORD*)malloc(sizeof(offsetArray));
  this->offsets = offsetArray;
};

首先,您使用malloc進行分配,在C ++中,由於malloc不調用任何構造函數,因此我們通常使用new。 第二個sizeof不提供數組的大小,而是給定指針的大小-與編寫sizeof(DWORD *)相同

然后,在為offsets分配了一些要指向的東西之后,然后讓它指向該參數,這樣使用malloc分配的字節就會泄漏。

在您的析構函數中,您假定offsetArray先前已分配有new []並傳遞給構造函數,但是您的類的用戶將如何知道呢?

想象有人使用分配在堆棧上的數組創建您的AddressInfo。

DWORD myArray[10];
AddressInfo adr = new AddressInfo(ammoCount,pointerLevel,baseAddress,offsetArray);

人們不想查看實現來尋找假設,即把東西放在類中以隱藏實現的整個想法。

在C ++中使用數組時,請改用std::arraystd::vector ,然后創建一個更加透明和簡潔的設計-請參閱Kilzone Kids答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM