How to implement class objects in header file C++

自作多情 提交于 2019-12-24 22:17:18

问题


How to implement class objects in a header file so every time I include the header file, I can access the object in the cpp file? Here is my code now:

//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;

however, when i use the member functions, it gives me no response:

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

On the other hand, this works.

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

Anyone knows how i can solve this problem?


回答1:


This is not complete answer, since there is too much unknown in what happens in your code, but rather explanation of how it can happen with wrong order of object creation.

Here is example:

#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;
}

You may think that 2 numbers in output will be both 5, but in reality first one may be anything (as per undefined behavior) and only second will be 5 because order of creation of objects in this particular case is:

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

But order of object initialization between different modules is undefined, i.e. there can be module in your code which calls initialize() in sequence of some object initialization before objects in module motor-config.cpp is initialized.



来源:https://stackoverflow.com/questions/57176331/how-to-implement-class-objects-in-header-file-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!