简体   繁体   中英

How to use typedef in header file cpp

I have created a new type using typedef and a struct. I want to export that type as a module.

I have the following cpp header file:

//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

This is the module file:

//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) {...}
};

And in this file, I create an object of the class Plane calling the constructor:

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

This throws the following error:

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

What causes this error and how can I resolve it?

I use the following command to compile:

g++ main.cpp header.h

You seem to be copying the Plane class's declaration, while an include is enough, so change your module.cpp file into something like:

#include "header.h"

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

Note that above does define what the header does declare , in C and C++, we can separate the declaration from definition
(I mean, method or function's {} body).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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