c用户定义的转换 – 隐式转换
发布时间:2020-12-16 09:57:30 所属栏目:百科 来源:网络整理
导读:参见英文答案 What is The Rule of Three?????????????????????????????????????8个 我有一个关于用户定义转换的问题. class String { char* m_data;public: String(): m_data(NULL) {} String(const char* cstr): m_data(new char[strlen(cstr)+1]) { strcp
|
参见英文答案 >
What is The Rule of Three?????????????????????????????????????8个
我有一个关于用户定义转换的问题. class String {
char* m_data;
public:
String(): m_data(NULL) {}
String(const char* cstr): m_data(new char[strlen(cstr)+1]) {
strcpy(m_data,cstr);
}
~String() {
delete[] m_data;
}
String& operator=(const char* cstr) {
delete[] m_data;
m_data = new char[strlen(cstr)+1];
strcpy(m_data,cstr);
return *this;
}
operator const char*() const {
return m_data;
}
};
虽然这有效: int main(int argc,char** argv) {
String a;
String b;
a = "aaa";
b = (const char *)a;
return 0;
}
这不是: int main(int argc,char** argv) {
String a;
String b;
a = "aaa";
b = a;
return 0;
}
我得到双重免费或损坏运行时错误. Valgrind说了一些关于无效删除的事情. 为什么我必须明确地对它进行类型转换?我认为它会以这种方式使用显式运算符const char *().难道我做错了什么? 解决方法
你忘了定义
copy assignment operator:
String& operator=(const String& other) {
if(this != &other) {
char* new_data = new char[strlen(other.m_data)+1];
strcpy(new_data,other.m_data);
delete[] m_data;
m_data = new_data;
}
return *this;
}
因此,您的编译器必须定义“默认”复制赋值运算符,简单地将“other”的所有字段分配给当前对象: String& operator=(const String& other) {
m_data = other.m_data;
return *this;
}
所以你有两个指向a和b中相同m_data的指针,并且在main的退出处,delete []将被调用两次. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
