简体   繁体   English

概念混乱

[英]Conceptual confusion

This might me a silly problem. 这可能是我一个愚蠢的问题。 But I am not getting the conceptual problem in the program. 但是我没有在程序中遇到概念上的问题。

I want to pass the pointer of class Child in a global function and access that pointer object from different parts of the project just by including Child.h 我想在全局函数中传递Child类的指针,并通过包含Child.h从项目的不同部分访问该指针对象

Problem: the following problem does not work when I do get_Child()->number_1 in the main. 问题:当我主要执行get_Child()-> number_1时,以下问题不起作用。

Solution: if I include the Child.cpp in the main, and inline the Constructor or if I declare the constructor in the Child.h instead of Child.cpp 解决方案:如果我在主目录中包含Child.cpp,并内联构造函数,或者如果我在Child.h中声明了构造函数,而不是Child.cpp

Query request. 查询请求。 What is the reason for this behavior? 这种行为的原因是什么? A way how I can declare the Constructor in Child.cpp and does not have to include Child.cpp in the main.cpp 我可以在Child.cpp中声明构造方法的方法,而不必在main.cpp中包含Child.cpp

main.cpp main.cpp

#include <iostream>
#include "Child.h"
//#include "Child.cpp"

using namespace std;

int main(){

    Child *pC = new Child();
    cout << "direct = " << pC->number_1 << endl;

    cout << "with function = " << get_Child()->number_1 << endl;

}

Child.h 儿童

#ifndef CHILD_H_
#define CHILD_H_


class Child;
static Child * pointer_Child;

inline void save_Child(Child * p_C){
    pointer_Child = p_C;
}

inline Child * get_Child(){
    return pointer_Child;
}


class Child {
public:

    Child();

    //Child(){
    //  this ->set_Child();
    //}

    void set_Child(){
        save_Child(this);
    }

    int number_1 = 10;
};

#endif /* CHILD_H_ */

Child.cpp Child.cpp

#include "Child.h"

//inline Child::Child(){
//  this ->set_Child();
//}

Child::Child(){
    this->set_Child();
}

Do not declare static variables in a header (outside of classes) like this: 不要在标头(类外部)中声明静态变量,如下所示:

static Child * pointer_Child;

It will create a variable in every compilation unit that includes the header. 它将在每个包含标头的编译单元中创建一个变量。 And they are not accessible from outside the translation unit. 并且它们不能从翻译单元外部访问。

Instead, make pointer_Child extern and provide an implementation in the CPP as follows: 相反,使pointer_Child extern并在CPP中提供一个实现,如下所示:

Header: 标头:

extern Child* pointer_Child;

CPP: CPP:

Child* pointer_Child;

And never include a CPP file. 而且永远不要包含CPP文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM