C const char *评估操作员超载
c++ const char * assigment operator overload
如何处理const char *
?
Obj(const Obj& o); // <--
Obj& operator=(const Obj& o);// <-- How to do it right?
// Obj(const Obj& o); // <--
// Obj& operator=(const Obj& o);
class Obj
{
protected:
const char * name;
const char * desc;
public:
Obj(const char * _name,
const char * _desc)
:name(_name)
,desc(_desc)
{
//
}
Obj(const Obj& o); // <--
Obj& operator=(const Obj& o);// <-- Have no idea how to implement this...
virtual ~Obj(){}
};
class B:public Obj
{
float v1, v2;
B(float a, float b)
:v1(a)
,v2(h)
,Obj("B","class")
{
//
}
};
更新
T& operator=(const T& other) // copy assignment
{
if (this != &other)
{ // self-assignment check expected
if (other.size != size)
{ // storage cannot be reused
delete[] mArray; // destroy storage in this
size = 0;
mArray = nullptr; // preserve invariants in case next line throws
mArray = new int[other.size]; // create storage in this
size = other.size;
}
std::copy(other.mArray, other.mArray + other.size, mArray);
}
return *this;
}
编辑:您的代码以Obj("B","class")
的形式有一个严重的错误,它会对成员进行外部指针而不是复制其数据。忘记所有,包括我的答案,然后使用std::string
。
用指针复制对象意味着您要序列化指针数据。如果是字符串,则strcpy/memcpy就足够了:
Obj& operator=(const Obj& o)
{
name = new char[o.namesize + 1]; // must keep the size unless it's a string, so you can assume the size with strlen().
strcpy_s(name,o.namesize + 1,o.name);
namesize = o.namesize;
// With strlen
name = new char[strlen(o.name) + 1];
strcpy_s(name,strlen(o.name) + 1,o.name);
return *this;
}
但是,始终使用std::string
并忘记所有这些内容,因为它将由STL自动处理,包括移动语义,自动内存管理等。