Ambitious
Ambitious

Reputation: 55

Learning C++ from a book cant get this programm working with classes

Main programm:

#include<iostream>
#include<string>
using namespace std;
#include "klasse_methoden.cpp"

int main(){

    postenTyp pEins;
    pEins.werteZuweisen(5,2.5,"Working?");
    pEins.ausgeben();

}

Class definition:

#include<string>
using namespace std;

class postenTyp{
    private:
        int anzahl;
        double kommaZahl;
        string name;
    public:
        void werteZuweisen(const int &, const double &, const string &);
        void ausgeben();
};

Class Methods:

#include "klasse_definition.cpp"
#include<iostream>


void postenTyp::werteZuweisen(const int &a, const double &p, const string &b){
    anzahl = a;
    kommaZahl = p;
    name = b;
}

void postenTyp::ausgeben(){
    cout << "Anzahl: " << anzahl << "Kommazahl: " << kommaZahl << "Name: " << name << endl;

}

Compile error - multiple definition

The book teaches me to not include anything or using namespace in the class definition and class methods but then i get even more errors.

Upvotes: 0

Views: 98

Answers (1)

Petok Lorand
Petok Lorand

Reputation: 973

You should include header files instead of source files.

This is true for both the klasse_methoden.cpp source file where you should include klasse_methoden.h and not vice versa and in the main.cpp also include klasse_methoden.h.

Also to avoid including the content of a header twice you need to use the pragma specifier #pragma once at the beginning of the header or use defines like this

#ifndef _MY_HEADER_GUARD_
    #define _MY_HEADER_GUARD_

//header content

#endif

Upvotes: 1

Related Questions