c++头文件问题
黄舟
黄舟 2017-04-17 12:59:37
0
6
784

若设计一个结构体三个类,和一堆宏定义以及一堆常量以及一堆全局函数:


#define ABC 1
#define DEF 2

int const MIN;

int funa(...);
int funb(...);

struct a;

class x;
class y;
class z;

其中,宏定义、常量、常量函数放在common.h中;
class x拥有一个成员变量是class y的实例;
class y拥有一个成员变量是class x的实例;
class z的大部分成员方法都会用到class xclass y

请问,如果要分成若干个.h文件和若干个.cpp文件,该如何写?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

Antworte allen(6)
Peter_Zhu

class x拥有一个成员变量是class y的实例;
class y拥有一个成员变量是class x的实例;

这。。除非是用指针,不然不可能


用指针如下:

common.h

#ifndef COMMON_H
#define COMMON_H

//宏定义
#define ABC 1
#define DEF 2

//结构定义
struct structA
{
    int a;
    int b;
    int c;
};


//常量声明
extern const int MIN;
const int MAX = 2;

//全局函数声明
extern const int funa();
extern int funb();


#endif

common.cpp

//全局函数实现
const int funa()
{
    return 0;
}
int funb()
{
    return 1;
}

//常量初始化
const int MIN = funa();

classx.h

#include "common.h"

class classy;

class classx{
    public:
        //classx成员声明
        int func();
        classy* _py;
};

classx.cpp

//classx成员函数实现
int classx::func()
{
}

classy.h

#include "common.h"

class classx;

class classy{
    public:
        //classy成员声明
        int func();
        classx* px;
};

classy.cpp

//classy成员函数实现
int classy::func()
{
}

classz.h

#include "classx.h"
#include "classy.h"

class classz{
    public:
        //classz成员声明
        classz();
        ~classz();
        classx* getX();
        classy* getY();
    private:
        classx* _x;
        classy* _y;
};

classz.cpp

#include "classz.h" 

//classz成员函数实现 
classz::classz()
{
    _x = new classx();
    _y = new classy();
}
         
classz::~classz()
{
    delete _x;
    delete _y;
}

classx* classz::getX()
{
    return _x;
}
classy* classz::getY()
{
    return _y;
}

main.cpp

#include <cstdio>
#include "classz.h"

int main()
{
    classz instancez;
    printf("%p %p", instancez.getX(), instancez.getY() );
    return 0;
}
Ty80

common.h

#define ABC 1
#define DEF 2

static int const MIN;

static int funa(...);
static int funb(...);

static struct a;

classx.h

#include "common.h"
class classy;

class x{
};

classy.h

#include "common.h"
class classx;

class y{
};

classz.h

#include "classx.h"
#include "classy.h"

class classz{
};
PHPzhong

楼主,你是怕循环引用,引起错误么?如果是这样,推荐你看看C++的类前置声明,这足以解决你的问题。

巴扎黑

反正是c++,常量应该可以全部变成constexpr啊。

巴扎黑

这不是前向声明能解决的。编译器在编译x类的时候需要知道完整的y类的定义,而要知道y类的完整定义就必须先知道x类的定义,编译器会告诉你“我搞不定”的。如果非要这样做,可以使用指针: x类有一个指向y类实例的指针,编译器是知道指针是什么东西的,同理用在y类上。

Ty80

这个就是使用前置声明,但是只能使用指针或者引用,因为编译器编译的时候必须明确成员的大小,而指针和引用的大小是确定的。

就好象设计房子和床,房子都还没设计好买床摆哪儿?大小尺寸未知,但是可以使用指针。

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!