作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面是我使用构造函数和复制构造函数创建的 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/
我是一名优秀的程序员,十分优秀!