【问题标题】:Overriding Functions result in multiple definitions error覆盖函数导致多个定义错误
【发布时间】:2020-02-28 20:43:36
【问题描述】:

我正在尝试设置一个 Employee 基本案例和一个 Hourly/Salied/Commissioned Employee 子类。当我尝试编译时,出现以下错误:

HourlyEmployee.o: In function `getInfo()':
/cygdrive/d/HourlyEmployee.cpp:4: multiple definition of `func1()'
Employee.o:/cygdrive/d/subclass.cpp:4: first defined here
HourlyEmployee.o: In function `getEarning()':
/cygdrive/d/HourlyEmployee.cpp:9: multiple definition of `func2()'
Employee.o:/cygdrive/subclass.cpp:9: first defined here

下面是我的代码,它非常简单,因为我只是试图设置函数的继承/覆盖。

子类.cpp

#include "subclass.h"

string func1(/* arguments */) {
  /* code */
  return 0;
}

double func2(/* arguments */) {
  /* code */
  return 0;
}

我在这里缺少什么?

【问题讨论】:

  • 您在函数定义之前缺少 classname::。又名 HourlyEmployee::getInfo

标签: c++ inheritance overriding


【解决方案1】:

定义成员函数时,必须使用ClassName:: 表示法,即

#include "HourlyEmployee.h"

string HourlyEmployee::getInfo(/* arguments */) {
  /* code */
  return 0;
}

double HourlyEmployee::getEarning(/* arguments */) {
  /* code */
  return 0;
}

【讨论】:

  • 成功了,谢谢!是否有可能在某些情况下不需要?具有相同项目的另一个人没有使用 ClassName:: 表示法,但他们的文件编译得很好。
  • 仅当您在类声明中定义时,例如class myClass:{ int GetInt() {return 1;}};,如果您在类声明之外并且不使用myClass::,您只是在定义与任何类无关的函数
猜你喜欢
  • 2018-07-21
  • 2020-09-26
  • 2010-12-03
  • 2012-07-20
  • 2014-01-27
  • 1970-01-01
  • 2013-07-12
  • 2020-02-04
  • 1970-01-01
相关资源
最近更新 更多