一个关于class的问题
本帖最后由 chn3698 于 2013-09-08 02:25:59 编辑 不知道标题是否和我的题目对的上去,但是我对此有点疑惑,自己也思考不出结果,所以只好来请教下各位前辈了
是这样的,我写了一个这样的类
class Mem
{
private:
int size;
unsigned char* bytes;
public:
Mem(int size)
{
this->size = 0;
this->bytes = nullptr;
/*
* 这部分是我把一个函数省略掉了写进来的
* 实际文件不是这样的,目的只是为了让前辈们知道这个类的作用
* 内容没整理,前辈们凑合一下吧
*/
if(this->size < size)
{
unsigned char* newBytes = new unsigned char[size];
memset(newBytes + size,0,size);
memcpy(newBytes,this->bytes,this->size);
delete[] this->bytes;
this->size = size;
this->bytes = newBytes;
}
}
unsigned char* getBytes()
{
return this->bytes;
}
//省略部分代码
}
//main.cpp 已包含相关文件
int main()
{
Mem mem(0);
char* data = "abcd";
/*
* 为何下面不能直接赋值?
* 我试过了两种方法,
* 一开始我尝试把data解引赋值给mem的bytes,但编译器报告说必须是可修改的左值
* 所以我就尝试直接把data赋值给bytes,但是编译器仍然报告说不是可修改的左值
*/
mem->getBytes() = *data;
mem->getBytes() = data;
return 0;
}
希望能有前辈为我指点迷经
[解决办法]
//首先这段代码写的很水,很多错误,delete [] 释放的是堆空间的
//而且释放之后就已经无效了! 自己再改改吧
unsigned char* newBytes = new unsigned char[size];
memset(newBytes + size,0,size);
memcpy(newBytes,this->bytes,this->size);
delete[] this->bytes;
this->size = size;
this->bytes = newBytes;
mem->getBytes() = *data;
mem->getBytes() = data;
//两个都是错的
//你调用调用接口你返回当前对象的数据给调用对象!
// 改下接口吧
getBytes(char *buf);
#include <iostream>
using namespace std;
class Mem
{
private:
int size;
char* bytes;
public:
Mem(int size)
{
this->size = 0;
this->bytes = nullptr;
/*
* 这部分是我把一个函数省略掉了写进来的
* 实际文件不是这样的,目的只是为了让前辈们知道这个类的作用
* 内容没整理,前辈们凑合一下吧
*/
if(this->size < size)
{
char* newBytes = new char[size];
memset(newBytes + size,0,size);
memcpy(newBytes,this->bytes,this->size);
delete[] this->bytes;
this->size = size;
this->bytes = newBytes;
}
}
char* getBytes()
{
return this->bytes;
}
//省略部分代码
void SetBytes(char* str)
{
this->bytes = str;
}
};
//main.cpp 已包含相关文件
int main()
{
Mem mem(0);
char* data = "abcd";
/*
* 为何下面不能直接赋值?
* 我试过了两种方法,
* 一开始我尝试把data解引赋值给mem的bytes,但编译器报告说必须是可修改的左值
* 所以我就尝试直接把data赋值给bytes,但是编译器仍然报告说不是可修改的左值
*/
//mem.getBytes() = data;
mem.SetBytes(data);
return 0;
}