【发布时间】:2020-08-01 08:12:15
【问题描述】:
为什么在这个 Friend 函数中调用析构函数show() C++? 还有,字符指针应该如何初始化,设置为0... main 的完整代码在这里https://justpaste.it/5x7fy
#include<iostream>
using namespace std;
#include<string.h>
class String
{
public:
char *p;
int len;
String()
{
cout << "empty constructor" << endl;
len=0;
p=0;
}
// constructor
String(const char *s) {
len=strlen(s);
p=new char[len+1];
strcpy(p,s);
}
friend String operator+(const String&s, const String&t);
friend int operator<=(const String&s, const String&t);
friend void show(const String s);
~String() {delete p;}
};
void show(const String s)
{
cout<<s.p<<endl;
}
编辑,阅读复制构造函数并添加一个:
// copy constructor
String(const String &s)
{
len=s.len;
p=new char[len+1]; // s.p;//
strcpy(p,s.p);
}
之前友元函数参数是传值,变量离开了show函数作用域,所以调用了析构函数,现在是传引用了。
friend void show(const String & s);
...
void show(String & s)
{
cout<<s.p<<endl;
}
Edit 更新了空构造函数中字符指针的初始化。
String() {
p = new char[1]{'\0'};
len = 1;
};
[最新来源]:https://www.mediafire.com/file/31gb64j7h77x5bn/class38working.cc/file
【问题讨论】:
-
不是你问的,但你上面的代码和链接的完整代码都没有正确的复制语义。因此,析构函数调用虽然正确,但可能会使您的程序崩溃。
-
说真的,教师应该在教授 the rule of three 之前停止教授内存泄漏。在大多数情况下忘记删除内存是无害的,无论如何程序都会很快结束,在没有适当的复制构造函数的析构函数中删除是UB。
-
@Yksisarvinen 是的,并且复制构造函数在以这种方式初始化时不起作用。}
String string3 = s1+s2
标签: c++ pointers destructor friend