3
可以說我有一個文件如何從一個文件中的朋友用其他文件中的類創建非成員函數?
//的Xh(第一文件)
#include <iostream>
class X{
int x;
public:
X(int i);
void print_me();
};
// X.cpp(第二文件)
#include "X.h"
X::X(int i){x = i}
void X::print_me(){std::cout<< x << endl;}
// main.cpp中(第三文件)
#include "X.h"
void swap(int lhs, int rhs){
// do the swap
}
class Y{
X x_obj;
public:
friend void swap(Y& lhs, Y& rhs){
swap(lhs.x_obj.x, rhs.x_obj.x);
}
};
int main(){return 0;}
我的問題是: 我怎樣才能讓Y類main.c中pp是X的朋友?
我在考慮將Y類分解成.h和.cpp文件,並將Y.h文件包含到X.h中並從那裏開始。除此之外,還有其他辦法嗎?我的意思是在代碼的當前狀況,使Y X的朋友:
我在目前的條件下得到的錯誤是:
> In file included from main.cpp:1:0: X.h: In function 'void swap(Y&,
> Y&)': X.h:3:9: error: 'int X::x' is private
> int x;
> ^main.cpp:12:24: error: within this context
> swap(lhs.x_obj.x, rhs.x_obj.x);
> ^In file included from main.cpp:1:0: X.h:3:9: error: 'int X::x' is private
> int x;
> ^main.cpp:12:37: error: within this context
> swap(lhs.x_obj.x, rhs.x_obj.x);
現在我遇到了非成員函數void swap(Y&lhs,Y&rhs)訪問Y的私有成員X x_obj的新問題,因爲此函數試圖訪問Y的私有成員。 – solti
@solti你已經聲明瞭它作爲'Y'級的朋友,不是嗎? – songyuanyao
yup ..出於某種原因,我想多次宣佈朋友創建問題..但顯然它沒有..後放置朋友無效交換(Y&lhs,Y & rhs);在Y中,因爲我早些時候做過它的工作 – solti