如何在头文件C ++中实现类对象 [英] How to implement class objects in header file C++

查看:289
本文介绍了如何在头文件C ++中实现类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

另一方面,这可行。

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

有人知道我如何解决这个问题吗?

Anyone knows how i can solve this problem?

推荐答案

这不是完整的答案,因为您的代码中发生了太多未知的事情,而只是解释了如何以错误的对象顺序发生它

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.

这里是示例:

#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 ,因为对象的创建顺序是这种特殊情况是:

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

但是不同模块之间对象初始化的顺序是不确定的,即代码中可以存在调用 initialize()在模块 motor-config.cpp 中的对象初始化之前,按一些对象初始化的顺序进行。

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.

这篇关于如何在头文件C ++中实现类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆