静态类和继承

时间:2012-03-30 17:00:07

标签: c++ inheritance static

我正在尝试使用相同的方法名称创建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:/var/folders/bg/171jl37d05v69c4t6t1tt03m0000gn/T//ccRJU6B9.o和/var/folders/bg/171jl37d05v69c4t6t1tt03m0000gn/T//ccVVSd1i.o中的复制符号person :: getQuantity() x86_64的 collect2:ld返回1退出状态

但是我为该特定类创建了静态方法。我该如何解决?

4 个答案:

答案 0 :(得分:3)

#include "person.cpp"

这是错误的。它将被编译两次。

您可能想要#include "person.h"

答案 1 :(得分:0)

解决了...问题是#include“person.cpp”

答案 2 :(得分:0)

问题是你在user.h的开头包含了person.cpp。这会导致person.cpp的内容被编译两次,因此您没有对该类的所有成员进行两次定义。你可能想包括person.h

答案 3 :(得分:0)

您在#include "person.cpp"中加入了User.h

将此更改为#include "person.h",一切都会好起来。

我尝试在进行此更改之后在Visual Studio 2010中编译代码,并且编译完所有。