gpt4 book ai didi

c++ - 如何更恰本地处理好友功能?

转载 作者:行者123 更新时间:2023-11-28 01:22:22 25 4
gpt4 key购买 nike

下面是我使用构造函数和复制构造函数创建的 String 类。我已经声明了一个包含函数 void print(String s); 的类 M,然后我尝试将类 M 的函数打印作为类 的 friend String 但它会给出编译时错误,提示 M 不存在。另一方面,如果我让类 M 成为类 String 的友元,那么令人惊讶的是代码可以正常工作。

#include<iostream>
#include<cstring>
using namespace std;
class String{
private:
char* str;
size_t len;
public:
String(char* str){
len=sizeof(str)/sizeof(char);
this->str=new char[(int)len];
strcpy(this->str,str);
}
String(const String& s){
if(str!=s.str)
{
strcpy(str,s.str);
len=s.len;
}
}
friend void M::print(String);//This line gives compile time error saying M does not exists.
// friend class M;//This line on the other hand works completely fine when uncommented
};
class M{
public:
void print(String s){
cout<<s.str;
}
};
int main()
{
char x[6]={'H','e','l','l','o','\0'};
String str=x;
M a;
a.print(str);
return 0;
}

最佳答案

在这个问题上,C++ 的行为相当不一致。使类 M 成为 friend 等同于转发声明此类。然而,使该类的方法成为友元需要定义该类:

class String;

class M{
public:
void print(String s);
};

class String {
// definition goes here...
friend void M::print(String); // now works because compiler is aware of M::print
};

void M::print(String s)
{
cout<<s.str;
}

关于c++ - 如何更恰本地处理好友功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55520163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com