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

标签 c++ oop c++11

考虑以下代码:

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/

相关文章:

C++ Hermite多项式实现

c++ - boost 不同的工具集

c++ - 确定无序 vector<T> 是否具有所有唯一元素

java - 内部类。它的目的是什么?

c# - 如何实现双向类?

c++ - 如何避免成员回调和 shared_ptr 的循环引用?

c# - 为新对象实例设置参数

c++ - 具有可变模板参数的函数指针

c++ - move 字符串流的 .str() 成员是否合法?

c++ - 是否可以为 std::array 定义隐式转换运算符?