我们可以声明一个没有参数的朋友函数吗?

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)


A. *_* H. 6

是的你可以。可能有很多原因,例如访问私有静态成员,或者可能存在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)


Ash*_*sha 5

当然你可以..请参阅此处的示例代码。但是要定义内联函数,您需要使用sampleas 参数,否则 ADL 将无法工作,编译器将无法解析func. 请参阅此处的示例。