首页 > 解决方案 > 为什么在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

标签: c++pointersdestructorfriend

解决方案


调用析构函数是因为s按值传递。也就是说,当您调用show(something)时,会将某些内容复制到s中,然后在执行show结束时将其销毁。


推荐阅读