【问题标题】:How to use typedef in header file cpp如何在头文件cpp中使用typedef
【发布时间】:2021-08-14 12:31:35
【问题描述】:

我使用 typedef 和结构创建了一个新类型。我想将该类型导出为模块。

我有以下cpp头文件:

//header.h
#ifndef VECTOR_H
#define VECTOR_H
typedef struct {
    float x;
    float y;
    float z;
} Vector;
#endif

#ifndef PLANE_H
#define PLANE_H
class Plane {
    public: 
        //this works
        Vector n;
        //this does not work
        Plane(Vector P1, Vector P2, Vector);
};
#endif

这是模块文件:

//module.cpp
#include header.h
typedef struct {
    float x;
    float y;
    float z;
} Vector;

class Plane {
    public: 
        Vector n;
        Plane(Vector P1, Vector P2, Vector P3) {...}
};

在这个文件中,我创建了一个调用构造函数的类Plane的对象:

//main.cpp
#include header.h
float distance = 10;

int main() {
    Vector P1 = { 0, 0, 11.5 };
    Vector P2 = { 0, distance, 10 };
    Vector P3 = { distance, distance, 5 };

    Plane E(P1, P2, P3);
    return 0;
}

这会引发以下错误:

undefined reference to `Plane::Plane(Vector, Vector, Vector)'

是什么导致了这个错误,我该如何解决?

我使用如下命令编译:

g++ main.cpp header.h

【问题讨论】:

标签: c++ oop g++ header-files


【解决方案1】:

您似乎在复制 Plane 类的声明,而一个包含就足够了,所以将您的 module.cpp 文件更改为:

#include "header.h"

Plane::Plane(Vector P1, Vector P2, Vector P3)
{
}

注意上面确实define标头做了什么declare,在C和C++中,我们可以将声明和定义分开
(我的意思是,方法或函数的 {} 主体)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 2023-03-20
    • 2016-04-06
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多