我正在阅读 Balagurusamy 的 C++ 面向对象编程中的“本地类”概念(http://highered.mcgraw-hill.com/sites/0070593620/information_center_view0/)。
最后一行说“封闭函数不能访问本地类的私有成员。但是,我们可以通过将封闭函数声明为友元来实现这一点。 ”
现在我想知道如何完成突出显示的部分?
这是我正在尝试但没有运气的代码,
#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;
}
Run Code Online (Sandbox Code Playgroud)
我知道代码看起来是错误的,任何帮助都是可观的。
声明friend int pqr(abc);没问题。它不起作用,因为abc在将其用作函数中的参数类型之前尚未定义该类型pqr()。在函数之前定义它:
#include<iostream>
// By the way, "using namespace std" can cause ambiguities.
// See http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.5
using namespace std;
// Class defined outside the pqr() function.
class abc
{
int x;
public:
int xyz()
{
return x=4;
}
friend int pqr(abc);
};
// At this point, the compiler knows what abc is.
int pqr(abc t)
{
t.xyz();
return t.x;
}
int main()
{
abc t;
cout<<"Return "<<pqr(t)<<endl;
}
Run Code Online (Sandbox Code Playgroud)
我知道你想使用本地类,但你所设置的不起作用。局部类仅在定义它的函数内部可见。如果要使用函数abc外部的实例pqr(),则必须在abc函数外部定义该类。
但是,如果您知道该类abc仅在函数内使用pqr(),则可以使用本地类。但在这种情况下,您确实需要friend稍微修改一下声明。
#include<iostream>
// By the way, "using namespace std" can cause ambiguities.
// See http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.5
using namespace std;
// pqr() function defined at global scope
int pqr()
{
// This class visible only within the pqr() function,
// because it is a local class.
class abc
{
int x;
public:
int xyz()
{
return x=4;
}
// Refer to the pqr() function defined at global scope
friend int ::pqr(); // <-- Note :: operator
} t;
t.xyz();
return t.x;
}
int main()
{
cout<<"Return "<<pqr()<<endl;
}
Run Code Online (Sandbox Code Playgroud)
在 Visual C++(编译器版本 15.00.30729.01)上进行编译时不会出现警告。
| 归档时间: |
|
| 查看次数: |
5555 次 |
| 最近记录: |