简体   繁体   中英

When seperating class file into .h and .cpp file how can I define it in the main file by including the .h file?

So I'm implementing a simple test class and such I'm separating files into: compte.h:

#ifndef COMPTE_H
#define COMPTE_H
#include <iostream>
class compte
{
public:
    static int n;
    int numCompte;
    char* nom;
    double solde;
public:
    compte(const char* = NULL, const double & = 0);
    ~compte();
};

and a compte.cpp

#include <iostream>
#include <cstring>
#include "compte.h"
using namespace std;

int compte::n = 1000;
    
compte::compte(const char* nom, const double &solde)
{
    this->solde = solde;
    this->nom = new char[strlen(nom)];
    strcpy(this->nom, nom);

    numCompte = n++;
}
compte::~compte()
{
    delete[] nom;
}

however, when I include compte.h I get an unidentified reference to the member methods of the class, when I include compte.cpp it works, I just want to know what I can add to include the.h file instead of.cpp

Your header file compte.h is missing an #endif in the end.

#ifndef COMPTE_H
#define COMPTE_H
#include <iostream>
class compte
{
public:
    static int n;
    int numCompte;
    char* nom;
    double solde;
public:
    compte(const char* = NULL, const double & = 0);
    ~compte();
};

#endif

This is a sample of main file you can test with

#include "compte.h"
#include <memory>
using namespace std;

int main()
{
    unique_ptr<compte> account = make_unique<compte>("account", 100);
    cout << account->solde; 
}

Compile and run:

g++ compte.h compte.cpp main.cpp -o main.exe

./main.exe

as a rule of thumb do NOT include *.c or *.cpp. You should include only headers of f. (and classes for C++), since the extension: "headers"

including *.ccp may work, if you include it ONCE in only one other file (in you example near main()), but it can lead to duplication of identifiers, as including in 2 files, will produce TWO source code (work dine by preprocessor) so TWO functions (classes...) code, so link will complain about it.

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