[C++]宏定义解决重定义

person.h

#include 
#include 
#include 
using namespace std;

class Person {
public:
    Person(string color="blue");
    virtual~Person();
    void printColor();
protected:
    string m_strColor;

};

person.cpp

#include "Person.h"

Person::Person(string color){
    m_strColor = color;
    cout << "Person()" << endl;
}

Person::~Person() {
    cout << "~Person()" << endl;
}

void Person::printColor() {
    cout << "printColor()" << endl;
}


Worker.h

#include "Person.h"

class Worker :public Person{
public:
    Worker(string name="workername",string color="green");
    ~Worker();

protected:
    string  m_strName;
};

Worker.cpp

#include "Worker.h"

Worker::Worker(string name, string color ) {
    m_strName = name;
    m_strColor = color;
    cout << "Worker()" << endl;
}

Worker::~Worker() {
    cout << "~Worker()" << endl;

}

Farmer.h

#include "Person.h"

class Farmer :public Person{

public:
    Farmer(string code="110",string color="yellow");
    ~Farmer();
protected:
    string m_strCode;
};

Farmer.cpp

#include "Farmer.h"

Farmer::Farmer(string code,string color) {
    m_strCode = code;
    m_strCode = color;

    cout << "Farmer()" << endl;
}

Farmer::~Farmer() {
    cout << "~Farmer()" << endl;
}

MigrantWorker.h

#include "Farmer.h"
#include "Worker.h"

class MigrantWorker :public Worker,public Farmer {

public:
    MigrantWorker(string name="migrantName",string code="119",string color="white");
    ~MigrantWorker();
    
};

MigrantWorker.cpp

#include "MigrantWorker.h"

MigrantWorker::MigrantWorker(string name,string code,string color): Farmer(name,color),Worker(code,color){

    cout << "MigrantWorker()" << endl;
}

MigrantWorker::~MigrantWorker() {
    cout << "~MigrantWorker()" << endl;
}

demo.cpp

#include "MigrantWorker.h"

int main() {

    MigrantWorker *p=new MigrantWorker("tong", "tcode", "tcolor");

    delete p;
    p = NULL;

    system("pause");
    return 0;
}

运行

“Person”:“class”类型重定义   

解决

#ifndef PERSON_H
#define PERSON_H

#include 
#include 
#include 
using namespace std;

class Person {
public:
    Person(string color="blue");
    virtual~Person();
    void printColor();
protected:
    string m_strColor;

};

#endif 

你可能感兴趣的:([C++]宏定义解决重定义)