如何在头文件C++中实现class个对象

How to implement class objects in header file C++

如何在头文件中实现 class 对象,以便每次包含头文件时,我都可以访问 cpp 文件中的对象?这是我的代码:

//motor-config.cpp
#include "core.hpp"
#define create_motor_group(x,y...) Motor_Group x ({y})
create_motor_group(fullDrive, frontLeft,rearLeft,frontRight,rearRight);
create_motor_group(leftDrive,frontLeft,rearLeft);
create_motor_group(rightDrive,frontRight,rearRight);
create_motor_group(lift,leftLift,rightLift);
create_motor_group(roller,leftRoller,rightRoller);
//motor-config.h
#include "core.hpp"
extern Motor_Group fullDrive;
extern Motor_Group leftDrive;
extern Motor_Group rightDrive;
extern Motor_Group lift;
extern Motor_Group roller;

但是,当我使用成员函数时,它没有给我任何响应:

//init.cpp
#include "motor-config.h"
void initialize(){
  llemu::init();
  initMove();
  leftDrive.move(127);
}

另一方面,这行得通。

//init.cpp
void initialize(){
  Motor_Group test({frontLeft,rearLeft})
  llemu::init();
  initMove();
  test.move(127);
}

有人知道我怎么解决这个问题吗?

这不是完整的答案,因为您的代码中发生的事情有太多未知数,而是解释错误的对象创建顺序如何发生。

示例如下:

#include <iostream>

int init();

struct A {
    A() {std::cout << "A constructor" << std::endl;}
    int a = 5;
};

struct B {
    B() {std::cout << "B constructor" << std::endl;}
    int b = init();
};

B b;
A a;
B other_b;

int init() {
    return a.a;
}

int main()
{
    std::cout << b.b << std::endl << other_b.b << std::endl;
}

你可能认为输出中的 2 个数字都是 5,但实际上第一个可能是任何东西(根据未定义的行为)只有第二个是 5 因为创建顺序在这种特殊情况下,对象的数量是:

B constructor of b
A constructor of a
B constructor of other_b

但是不同模块之间的对象初始化顺序是未定义的,即您的代码中可以有模块在初始化模块 motor-config.cpp 中的对象之前按某些对象初始化的顺序调用 initialize()