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

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


#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文件,该如何写?

黄舟
黄舟

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

全部回覆(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

雷雷

classx.h

雷雷

classy.h

雷雷

classz.h

雷雷
PHPzhong

樓主,你是怕循環引用,引起錯誤麼?如果是這樣,推薦你看看C++的類別前置聲明,這足以解決你的問題。

巴扎黑

反正是c++,常數應該可以全部變成constexpr啊。

巴扎黑

這不是前向聲明能解決的。編譯器在編譯x類別的時候需要知道完整的y類別的定義,而要知道y類別的完整定義就必須先知道x類別的定義,編譯器會告訴你「我搞不定」的。如果要這樣做,可以使用指針: x類別有一個指向y類實例的指針,編譯器是知道指針是什麼東西的,同理用在y類上。

Ty80

這就是使用前置聲明,但是只能使用指標或引用,因為編譯器編譯的時候必須明確成員的大小,而指標和引用的大小是確定的。

就好像設計房子和床,房子都還沒設計好買床擺哪裡?大小尺寸未知,但是可以使用指針。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板