<分区>
我最近开始学习c++(我已经有中级的c)。我了解构造函数背后的思想及其工作原理,但我不明白为什么当我使用 new 创建 Packet 对象时,构造函数中的 malloc 返回 NULL/0x0 内存位置。如果我定义一个 Packet 对象,我对构造函数中的 malloc 没有问题。 这是代码,希望对格式/编码进行任何更正:
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
class Packet
{
public:
unsigned int size_pck;
char *packet_data;
Packet(unsigned int size)
{
size_pck=size;
char *packet_data=(char *)malloc(size);
}
~Packet()
{
free(packet_data);
}
};
int main (void)
{
Packet *created_pck;
created_pck=new Packet(4);
return 0;
}