簡體   English   中英

無法理解為什么朋友功能不起作用

[英]Not able to understand why friend function is not working

#include<iostream>
using namespace std;

class A;
void test(A &a);
class A
{
    private:
        int x;
        int y;
        friend void test();
};
void test(A &a)
{
    a.x = 1;
    a.y = 2;
    cout << a.x << " " << a.y << endl;
}
int main()
{
    A a;
    test(a);
}

我得到的錯誤如下-

1.error: 'int A::x' 在這個上下文中是私有的

2.error: 'int A::y' 在這個上下文中是私有的

友元函數不是應該能夠修改類的私有成員嗎?

#include <iostream>
using namespace std;

class A { 
  private: 
    int x; 
    int y; 

  public: 
    friend void test(A &); 
};

void test(A &a) { 
  a.x=1; 
  a.y=2; 
  cout << a.x << " " << a.y << endl; 
}

int main() { 
  A a; 
  test(a); 
}

我的代碼有錯誤:我在類中給出的朋友定義是錯誤的

#include<iostream>
using namespace std;

class A;
void test(A &a);
class A
{
    private:
        int x;
        int y;
        friend void test(A &a);
};
void test(A &a)
{
    a.x = 1;
    a.y = 2;
    cout << a.x << " " << a.y << endl;
}
int main()
{
    A a;
    test(a);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM