我不断收到错误,因为 A 类是私有(private)成员。我想避免将它们公开。我认为让 A 的 B 类 friend 可以解决这个问题。
我在 2 个不同的头文件中创建了 2 个类,如下所示:
啊
class A {
friend class B;
private:
std::string id;
std::string name;
std::string label;
public:
A();
~A() {};
};
B.h
#include "A.h"
class B {
friend class A;
private:
std::string num;
std::string data;
std::vector<A> vec;
public:
B();
friend int display(B&);
~B() {};
};
B.cpp
int display(B& b){
// TESTING
b.vec.resize(5);
b.vec[0].id = "test";
cout << b.vec[0].id << endl;
return 1;
}
错误:
error: 'std::__cxx11::string A::id' is private within this context
最佳答案
std::vector<std::shared_ptr<A>>
作为 B 的成员,其中 A 是一个接口(interface))关于c++ - 在 A 类中创建一个类型为 B 类的 vector - 问题访问数据 [C++] [成员在两个类中都是私有(private)的],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60029283/