2012-03-30 202 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中编译您的代码。