我有兩個類,即X和Y;我可以在C++中執行以下操作:
X Y
foo () bar ()
Y只在X類中使用foo函數。我可以在C++中執行以下操作嗎?
friend bool Y :: bar (X & (X :: foo))
即Y
具有在未經許可的僅到達X
對象的foo
功能?
編輯:是X & (X :: foo)
用法正確嗎?
我有兩個類,即X和Y;我可以在C++中執行以下操作:
X Y
foo () bar ()
Y只在X類中使用foo函數。我可以在C++中執行以下操作嗎?
friend bool Y :: bar (X & (X :: foo))
即Y
具有在未經許可的僅到達X
對象的foo
功能?
編輯:是X & (X :: foo)
用法正確嗎?
不,你不能。但你可以做到以下幾點:
class X_foo_friend;
class X
{
void foo();
friend class X_foo_friend;
};
class Y
{
X x;
public:
void bar();
};
class X_foo_friend
{
static void foo(X& x);
friend void Y::bar();
};
void X::foo() {};
void X_foo_friend::foo(X & x) { x.foo(); }
void Y::bar()
{
X_foo_friend::foo(x);
}
國際海事組織,這是相當愚蠢的。我的意思是,你是設計X和Y的人,所以你可以簡單地限制你在X的函數中使用Y.
如果我理解你的問題正確的話,你想是這樣的:
class X;
class Y {
public:
void bar(X& x);
void baz(X& x);
};
class X {
void foo() { }
friend void Y::bar(X& x);
};
void Y::bar(X& x)
{
x.foo();
}
void Y::baz(X&)
{
// the following would be an error
// baz wasn't befriended with X
// x.foo();
}
int main()
{
X x;
Y y;
y.bar(x);
}
注意聲明和定義的順序,你需要像這樣,所以你實際上可以做一些與X
有用的內部Y::bar()
。但是,如果不考慮這樣做的話,那麼這是一個好主意。如果你摔倒了,你只需要交朋友的「分數」,那麼也許你的班級承擔了太多的責任。
我可能會探索一個使用ADL概念的中間代理。這當然是展示這個概念的部分實現。
namespace XNProxy {
class XNP;
}
namespace XN
{
using XNProxy::XNP;
class X {
friend void f(X *);
private:
void foo() { };
};
void f(X* p) {
X x;
x.foo();
}
}
namespace XNProxy
{
class XNP { };
using XN::X;
void f(XNP *) {
f((XN::X *)nullptr);
}
};
namespace YN
{
class Y {
public:
void bar() {
XNProxy::XNP x;
f((XNProxy::XNP*)nullptr);
}
};
}
int main() {
YN::Y y;
y.bar();
}
你在問什麼不清楚,標題措辭不好。嘗試修復帖子。 –
所以你想X :: foo只能從Y :: bar訪問? – Chubsdad
@Chubsdad yes .. – jques