我正在阅读Balagurusamy(http://highered.mcgraw-hill.com/sites/0070593620/information_center_view0/)的C++面向对象编程中的“本地类”概念。
最后一行说:“封闭函数无法访问本地类的私有(private)成员。但是,我们可以通过将封闭函数声明为 friend 来实现此目的。”
现在我想知道突出显示的部分如何完成?
这是我尝试的代码,但是没有运气,
#include<iostream>
using namespace std;
class abc;
int pqr(abc t)
{
class abc
{
int x;
public:
int xyz()
{
return x=4;
}
friend int pqr(abc);
};
t.xyz();
return t.x;
}
int main()
{
abc t;
cout<<"Return "<<pqr(t)<<endl;
}
我知道代码看起来是错误的,任何帮助都是可取的。
最佳答案
您的friend
语句很好。
int pqr() {
class abc {
int x;
public:
abc() : x(4) { }
friend int pqr();
};
return abc().x;
}
int main() {
cout << "Return " << pqr() << endl;
}
编辑:
IBM针对注释中提出的问题提供了以下解释:
void a();
void f() {
class A {
// error: friend declaration 'void a()' in local class without prior decl...
friend void a();
};
}
资料来源:IBM - Friend scope (C++ only)
所以,你很不幸。 Balagurusamy的技巧仅适用于MSVC和类似的编译器。您可以尝试将执行交给本地类内部的静态方法来解决:
int pqr() {
class abc {
int x;
public:
abc() : x(4) { }
static int pqr() {
return abc().x;
}
};
return abc::pqr();
}