gpt4 book ai didi

c++ - 在B类中访问A类的函数f,而f需要访问B的成员变量

转载 作者:太空狗 更新时间:2023-10-29 22:55:29 25 4
gpt4 key购买 nike

考虑以下代码:

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_keysm_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
}

我该如何设计?我不断收到错误。我想我必须使用类似的东西:类前向声明​​、 friend 等提前致谢。ps: 我仅限于 c++11

最佳答案

只需将汽车作为 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;
}

I have to note, this way to do the job is not a good design, but sufficient for the beginning

关于c++ - 在B类中访问A类的函数f,而f需要访问B的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51894784/

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