gpt4 book ai didi

c++ - 使用友元类访问私有(private)数据成员

转载 作者:行者123 更新时间:2023-11-28 06:28:57 25 4
gpt4 key购买 nike

<分区>

我了解到,将一个类声明为友元类可以使它使用声明它的类的内容或成员。我使用了以下代码:

#include <iostream>

using namespace std;

class two; // forward class declaration
class one {
private:
friend class two; // friend class declared
int a; // to be accessed later
public:
one() { a = 5; }
};

class two {
private:
int b;

public:
two() {
b = a; // intended to access 'a' and assign to 'b'
cout << " " << b << endl;
}
};

int main() {
one one_obj;
two two_obj;
return 0;
}

错误是:'a' 未在此范围内声明

我在 friend 类的大多数示例中注意到的是,构造函数“two()”将使用“class one”作为参数,然后使用数据成员“a”。但我并不总是想创建一个新对象作为构造函数 two() 的参数。例如,调用构造函数 one() 已经完成,并且已经设置了 'a' 的值。制造一个新物体意味着再做一次,这可能不太受欢迎。所以这一切导致的是,我可以使用 friend 类访问类的成员而不必再次声明对象吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com