Dix*_*gla 8 c++ class friend-function
可能吗?
class sample {
private:
int x;
public:
friend void fun();
};
Run Code Online (Sandbox Code Playgroud)
friend 函数没有参数!
在我看来不可能
因为朋友函数不是类的"成员"所以我们不能用类对象调用
喜欢:
sample s;
s.fun();
Run Code Online (Sandbox Code Playgroud)
jua*_*nza 16
是的你可以:
void fun()
{
sample s;
s.x++; // OK, fun() is a friend of sample
}
Run Code Online (Sandbox Code Playgroud)
要么
sample globalSample; // yikes, a global variable
void fun()
{
int i = globalSample.x; // OK, fun() is a friend of sample
}
Run Code Online (Sandbox Code Playgroud)
是的你可以。可能有很多原因,例如访问私有静态成员,或者可能存在sample. 也可以fun创建 的实例sample并获取其私有信息。
函数创建实例并用它做事的工作示例:
#include <iostream>
class sample {
private:
int x;
public:
friend void fun();
};
void fun()
{
sample s;
s.x = 555555555;
std::cout << s.x;
}
int main(){
fun();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
全局实例的示例:
#include <iostream>
#include <string>
class sample {
private:
int x;
public:
friend void fun();
};
sample s;
void fun()
{
s.x = 555555555;
std::cout << s.x;
}
int main(){
fun();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
私有静态成员的示例:
#include <iostream>
#include <string>
class sample {
private:
int x;
static const int w = 55;
public:
friend void fun();
};
void fun()
{
std::cout << sample::w;
}
int main(){
fun();
return 0;
}
Run Code Online (Sandbox Code Playgroud)