【发布时间】:2015-12-05 12:22:21
【问题描述】:
所以我想在我的类中有一个常量指针作为字段,因为它必须始终指向第一个单元格。问题是我不能这样做,因为我在构造函数中分配内存。我在考虑初始化列表,但分配的内存取决于参数的大小;在 C# 中,我会使用 ,,readonly''。不知道如何在 C++ 中做到这一点
class Package{
private: char *const pack ; // <-- here
public: Package(PackInfo pckInfo, Data file) ;
public: ~Package();
};
Package::Package(PackInfo pckInfo, Data data){
this->headerSize = sizeof(pckInfo);
this->sizeOfData = data.GetDataSize();
//alocate memory
this->pack = new char[this->sizeOfData + this->headerSize](); //<- can not be done
//pointer on the begining of allocated array
PackInfo *temp = (PackInfo*) this->pack;
//putting header information in the begining of the array // moving pointer at cell just after header information
*temp = pckInfo; temp++;
char *packPointer = (char*)temp;
//getting data from file direclty into the array
data.GetCurrentBytes(packPointer);
}
【问题讨论】:
-
为什么做不到? : pack(new char[sizeof(pckInfo)+data.GetDataSize()])
-
实际上如果在类定义中的 headerSize 和 sizeOfData 之后声明了 pack,您可以同时设置它们,然后毫无问题地分配数组,例如:headerSize(sizeof(pckInfo)), sizeOfData(..),包(新字符[headerSize+sizeOfData])
-
omg,我试过了,但似乎我做错了,我认为不能这样做。谢谢!!!!
-
一般来说,您不能将对象二进制转储到文件并返回并期望它能够正常工作。