[英]Why C++ friendship for function inside a class does not work same as a standalone function?
我想知道為什么以下兩個代碼之一編譯而另一個不編譯。 在第一個代碼中,createB 是一個獨立的 function。 在第二個代碼中,function createB 是 class A 的成員。
第一個編譯。
#include <iostream>
class A;
class B {
public:
B() { std::cout << "B"; }
friend B createB();
};
class A {
public:
A() { std::cout << "A"; }
};
B createB() { return B(); }
int main() {
A a;
B b = createB();
}
第二個沒有。
#include <iostream>
class A;
class B {
public:
B() { std::cout << "B"; }
friend B A::createB();
};
class A {
public:
A() { std::cout << "A"; }
B createB() { return B(); }
};
int main() {
A a;
B b = a.createB();
}
在第一個片段中, createB
是一個免費的(獨立的)function,並且友元聲明不一定要命名一個現有的 function。 所以這可行,並且還隱式聲明了一個名為createB
的 function,其返回類型為B
在全局命名空間中,盡管此createB
通過普通查找是不可見的。
第二個示例中的問題是A
在朋友聲明的點是不完整的, friend BA::createB();
.
為了解決這個問題,我們可以將A
的定義移到B
之前,這樣A
在友元聲明處是完整的。 此外,我們可以在定義B
之后提供createB
的定義,如下所示:
//forward declaration so that B can be used in declaration B createB();
class B;
class A {
public:
A() { std::cout << "A"; }
//this is declaration
B createB();
};
class B {
public:
B() { std::cout << "B"; }
friend B A::createB(); //this works as now at this point A is complete since we moved the definition of A to before B
};
//this is definition
B A::createB() { return B(); }
int main() {
A a;
B b = a.createB();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.