请阅读代码以了解问题:
#include <iostream>
void fun(int value)
{
//starts local class definition
class test
{
int x;
public:
test(int a) : x(a) {}
void display() const
{
std::cout << "x = " << x << std::endl;
}
};
//end of the definition
test t1(value);
t1.display();
//if we write the statement t1.x=100; here .It will give us an error
//because we can not access the private members from the enclosing function
//now what should I do if I want to access the private members of the test class from fun function
}
int main()
{
fun(5);
}
我是否应该将有趣的功能作为本地类(测试)的朋友。我正在读一本书,据说我们可以通过将封闭函数声明为friend
. 现在我的问题是我不知道如何将封闭函数作为本地类的朋友。请有人告诉我我该怎么做。