Hap*_*tal 0 c++ constructor copy
我正在尝试下面的代码,我明确定义了copy c'tor来解决别名问题.
但代码给出了运行时错误.
#include<iostream>
#include<cstring>
using namespace std;
class word
{
public:
word(const char *s) // No default c'tor
{
str=const_cast<char*>(s);
cnt=strlen(s);
}
word(const word &w)
{
char *temp=new char[strlen(w.str)+1];
strcpy(temp,w.str);
str=temp;
cnt=strlen(str);
}
~word()
{
delete []str;
cout<<"destructor called"<<endl;
}
friend ostream& operator<<(ostream &os,const word &w);
private:
int cnt;
char *str;
};
ostream& operator<<(ostream &os,const word &w)
{
os<<w.str<<" "<<w.cnt;
return os;
}
word noun("happy");
void foo()
{
word verb=noun;
cout<<"inside foo()"<<endl;
cout<<"noun : "<<noun<<endl<<"verb : "<<verb<<endl;
}
int main()
{
cout<<"before foo()"<<endl<<"noun : "<<noun<<endl;
foo();
cout<<"after foo()"<<endl<<"noun : "<<noun<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题出在这个构造函数中:
word(const char *s) // No default c'tor
{
str=const_cast<char*>(s);
cnt=strlen(s);
}
Run Code Online (Sandbox Code Playgroud)
在这里,您没有分配任何内存来将字符串复制到str变量中.但是在你正在做的类的析构函数中delete[] str;,因为str未使用new[]它分配的内存正在崩溃.您需要分配与复制构造函数中的内存类似的内存,并将字符串复制到新分配的内存中.或者更好的是,使用std::string.
编辑:如果你真的不想std::string出于某种原因使用,你还需要一个赋值操作符,检查@icabod提到的自我赋值.
| 归档时间: |
|
| 查看次数: |
412 次 |
| 最近记录: |