考虑以下代码:
class Car
{
public:
bool openCar();
}
class LocomotiveEngineer
{
public:
bool carRepair();
private:
std::list<int> m_screwdriver;
std::vector<int> m_keys;
Car myCar;
}
int main() {
LocomotiveEngineer peter;
}
我要解决的问题是允许carRepair()
和openCar()
的实现满足以下两个条件:
carRepair()
呼叫openCar()
openCar()
可以访问m_keys
和m_screwdriver
。 (通过LocomotiveEngineer或其他实例)这意味着在LocomotiveEngineer的cpp中,我想做类似的事情:
LocomotiveEngineer::carRepair()
{
openCar(); //carRepair() calls openCar()
}
在Car的cpp中,我喜欢:
Car::openCar()
{
m_keys.size(); //openCar() can access m_keys via an instance of LocomotiveEngineer or whatever
m_screwdriver.empty(); //openCar() can access m_screwdriver via an instance of LocomotiveEngineer or whatever
}
我该如何设计?我一直在犯错误。我想我很想像这样:类转发声明,朋友等 提前致谢。 ps:我仅限于c ++ 11
答案 0 :(得分:1)
只需将汽车作为friend
添加到LocomotiveEngineer类中即可:
class LocomotiveEngineer
{
public:
bool carRepair();
private:
std::list<int> m_screwdriver;
std::vector<int> m_keys;
friend class Car;
}
但是,您当然必须拥有一个机车工程师的实例 或将工程师变量声明为静态变量;
如果您想进一步指定friend
关键字,也可以只使用friend bool Car::openCar();
而不是friend class Car;
代替特定的函数,而不是整个类。
工作示例
标题:
#include <vector>
class LocomotiveEngineer; // forward declare
class Car
{
public:
bool openCar(LocomotiveEngineer& repairmen);
}
class LocomotiveEngineer
{
public:
bool carRepair(Car& broken_car); //specify the car whcih needs to be repaired
private:
std::list<int> m_screwdriver;
std::vector<int> m_keys;
friend class Car;
}
cpp:
bool LocomotiveEngineer::carRepair(Car& broken_car)
{
broken_car.openCar(*this);
return true;
}
bool Car::openCar(LocomotiveEngineer& repairmen){
repairmen.m_keys.size(); //openCar() can access m_keys
repairmen.m_screwdriver.empty(); //openCar() can access m_screwdriver
return true;
}
主要*
int main(){
Car brokenCar;
LocomotiveEngineer bob;
bob.carRepair(brokenCar);
return EXIT_SUCCESS;
}
我必须注意,这种工作方式不是一个好的设计,但对于开始来说足够了