c++ - 为什么在Friend函数中调用析构函数
问题描述
为什么在这个 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;
}
编辑更新了空构造函数中字符指针的初始化。
String() {
p = new char[1]{'\0'};
len = 1;
};
【最新来源】:https ://www.mediafire.com/file/31gb64j7h77x5bn/class38working.cc/file
解决方案
调用析构函数是因为s
按值传递。也就是说,当您调用show(something)
时,会将某些内容复制到s
中,然后在执行show
结束时将其销毁。
推荐阅读
- python - 如何使用输入框设置变量
- haskell - 我可以概括 Haskell 中的类约束吗?
- graphql - 如何修复“错误:GraphQL 错误:无法读取未定义的属性 'id'”?
- splunk - 根据其他字段的值计算一个字段的值
- c++ - 具有多线程支持的 RenderClass,将函数调用推送到向量以在另一个线程上调用
- swift - Swift SQLite 查询不返回任何结果
- docker - Terraform 不在工作节点上创建 docker 服务
- python - 在多级层次结构 Pandas Dataframe 中更改索引
- elasticsearch - Kibana 服务器还没有准备好
- javascript - 如何在 JavaScript 代码中从 ModelAndView 访问变量