2012-03-30 102 views
0

我正試圖用相同的方法名創建2個類。 它的一個練習,所以我不能改變行爲。靜態類和繼承

Person.h

#ifndef __PERSON__ 
#define __PERSON__ 
#include <iostream> 

using namespace std; 


class person{ 
protected: 
    string name; 
    static int quantity; 
private: 

public: 
    person(); 
    ~person(); 
    string getName() const; 

    static void add(); 
    static int getQuantity(); 

}; 
#endif 

person.cpp

#include "person.h" 

int person::quantity=0; 
person::person(){} 
person::~person(){} 
string person::getName() const{ 
    return this->name; 
} 


int person::getQuantity(){ 
    return person::quantity; 
} 

user.h

#ifndef __USER__ 
#define __USER__ 
#include <iostream> 
#include "person.cpp" 

using namespace std; 


class user:public person{ 
private: 
    int age; 
    static int quantity; 

public: 
    user(); 
    ~user(); 

    static int getQuantity(); 
    static void add(); 

    int getAge(); 
    void setAge(int age); 


};    
#endif 

user.cpp

#include "user.h" 

int user::quantity=0; 

user::user():person(){} 
user::~user(){} 

int user::getQuantity(){ 
    return user::quantity; 
} 
void user::add(){ 
    user::quantity++; 
} 
int user::getAge(){ 
    return this->age; 
} 
void user::setAge(int age){ 
    if(age>=0)this->age=age; 
} 

問題是ld:重複符號person :: getQuantity()在/var/folders/bg/171jl37d05v69c4t6t1tt03m0000gn/T//ccRJU6B9.o和/var/folders/bg/171jl37d05v69c4t6t1tt03m0000gn/T//ccVVSd1i.o架構x86_64 collect2:ld返回1退出狀態

但我創建該特定類的靜態方法。我該如何解決這個問題?

+2

包含雙下劃線的標識符被保留用於實現。這也適用於宏名稱。 – 2012-03-30 17:03:20

+1

'在標頭中使用namespace std;'也是不好的形式。 – Mat 2012-03-30 17:04:54

回答

0

解決...問題是將#include「person.cpp」

0

的問題是要包括在user.h.年初person.cpp這會導致person.cpp的內容被編譯兩次,所以沒有這個類的所有成員有兩個定義。你可能指包括person.h

2

#include "person.cpp" 

這是不對的。它會被編譯兩次。您可能想要#include "person.h"

0

您在User.h中包括#include "person.cpp"

更改爲#include "person.h",一切都會好起來的。

我試圖在進行此更改並編譯好之後,在Visual Studio 2010中編譯您的代碼。