提供LNK1169错误的抽象类程序

时间:2018-12-01 20:30:55

标签: c++ virtual abstract void

我正在使用抽象类开发cpp程序。显然,编译器不接受我声明了抽象类和派生类的事实。我有不同的文件(.cpp和.h)。错误如下:

1> IGeomObj.obj:错误LNK2005:“公共:虚拟void __thiscall IGeomObj :: circumference(void)”(?circumference @ IGeomObj @@ UAEXXZ)已在GeoRect.obj中定义

1> main.obj:错误LNK2001:未解决的外部符号“ public:虚拟void __thiscall GeoRect :: circumference(void)”(?circumference @ GeoRect @@ UAEXXZ)

1> IGeomObj.exe:致命错误LNK1120:1个未解决的外部组件 ===========构建:0成功,1失败,0最新,跳过0 ==========

这里是代码: main()

 # include <iostream>
 # include "IGeomObj.h"
 # include "GeoCircle.h"
 # include "GeoEllipse.h"
 # include "GeoRect.h"
 # include "GeoSquare.h"
 # include "GeoTriangle.h"

 using namespace std;

 int main()
 {
/*GeoSquare *R;
GeoTriangle *R;
GeoRect *R;
GeoRect *R;*/
int opt;
do{
    cout<<endl<<"Menu:"<<endl<<endl<<"0.    Exit"<<endl<<"1.    New rectangle"
        <<endl<<"2. New Square"<<endl<<"3.  New Triangle"<<endl<<"4.    New        Circle"<<endl
        <<"5.   New Ellipse"<<endl;
        cin>>opt;
    switch(opt)
    {
    case 0:
        break;
    case 1:
        GeoRect *R=new GeoRect;
        cout<<endl<<"Height of the rectangle: ";
        cin>>R->h;
        cout<<endl<<"Width of the rectangle: ";
        cin>>R->b;
        R->output();
        break;

    };
}while(opt!=0);

system("pause");
return 0;
}

IGeomObj.h

 #pragma once
 #ifndef IGEOMOBJ_H
 #define IGEOMOBJ_H

 #include <iomanip>
 #include <fstream>

 class IGeomObj{

 public:

float b,h,r,f,u;
virtual void output()=0;
virtual void area()=0;
virtual void circumference()=0;
};
#endif

IGeomObj.cpp

 #include "IGeomObj.h"
 #include <iostream>
 using namespace std;

 void IGeomObj::output(){};
 void IGeomObj::area(){};
 void IGeomObj::circumference(){};

GeoRect.h

 #pragma once
 #ifndef GEORECT_H
 #define GEORECT_H

 #include <iomanip>
 #include <fstream>
 #include "IGeomObj.h"

 class GeoRect:public IGeomObj
 {
 public:
    virtual void output();
    virtual void area();
    virtual void circumference();
 };

 #endif

GeoRect.cpp

  #include "GeoRect.h"
  #include <iostream>
  using namespace std;

  void GeoRect::output()
  {  
    cout<<"Rectangle Area: "<<this->f<<" Circumference: "<<this->u;
  };

  void GeoRect::area()
  {
  this->f=this->h*this->b;
  };

  void IGeomObj::circumference()
   {
     this->u=2*this->h+2*this->b;
   };

2 个答案:

答案 0 :(得分:0)

您的GeoRect.cpp文件实现IGeomObj::circumference(),这是合法的,因为您可以提供纯虚拟功能的实现。

但是,这还不够吗?您还没有实现GeoRect::circumference(),这是必需的,因为将基类函数声明为纯虚函数。

答案 1 :(得分:0)

在GeoRect.cpp中,您有IGeomObj::circumference的定义。

void IGeomObj::circumference()
{
   this->u=2*this->h+2*this->b;
};

但这应该是GeoRect的定义。

void GeoRect::circumference()
{
   this->u=2*this->h+2*this->b;
};

对于成员的每次引用也不必添加this->

void GeoRect::circumference()
{
   u=2*h+2*b;
};