2017-03-18 49 views
-1
#include <iostream> 
using namespace std; 

class S; 

class R { 
     int width, height; 
     public: 
     int area() // Area of rectangle 
    {return (width * height);} 
    void convert (S a); 
}; 
class S { 
    private: 
    int side; 
    public: 
    S (int a) : side(a) {} 
    friend void convert(S a); 

}; 

void R::convert (S a) {  
    width = a.side; 
    height = a.side; // Interpreting Square as an rectangle 
} 
int main() { 

    int x; 

    cin >> x; 
    R rect; 
    S sqr (x); 
    rect.convert(sqr); 
    cout << rect.area(); 
    return 0; 
} 

我收到以下錯誤訪問私有成員:無法通過友元函數

prog.cpp: In member function ‘void R::convert(S)’: prog.cpp:26:14: error: ‘int S::side’ is private within this context width = a.side; ^~~~ prog.cpp:16:8: note: declared private here int side; ^~~~ prog.cpp:27:15: error: ‘int S::side’ is private within this context height = a.side; // Interpreting Square as an rectangle ^~~~ prog.cpp:16:8: note: declared private here int side; ^~~~

我試圖把友元函數功能也私,但同樣的錯誤。 請幫助

class S
+0

朋友是在S級不是R中...... –

回答

0

你應該有friend R;

friend void convert(S a);是無意義的,因爲編譯器甚至不知道轉換屬於R值不要S.

+0

感謝您的解決方案:) –

0

對於初學者名稱S未聲明之前,它是在聲明中首次使用

void convert (S a); 

其次,你必須指定該功能convert是MEMB呃類功能R

請嘗試以下

class R { 
     int width, height; 
     public: 
     int area() // Area of rectangle 
    {return (width * height);} 
    void convert (class S a); 
        ^^^^^^ 
}; 
class S { 
    private: 
    int side; 
    public: 
    S (int a) : side(a) {} 
    friend void R::convert(S a); 
       ^^^ 
};