"Undefined reference" 使用继承和纯虚函数时出错

"Undefined reference" error while using inheritance and pure virtual functions

当我制作矩形类型的对象时报错并说未定义引用。请解决。 我可能犯了一些错误,因为我对虚函数的概念很模糊

#include <iostream>
#include <cmath>
#include <conio.h>
using namespace std;


class shape{
protected:
string type;
float width;
float height;
public:
shape(){
    type = "shape";
    width = 0;
    height = 0;
}

string getType(){
    return type;
}

float getWidth(){
    return width;
}

float getHeight(){
    return height;
}

void setType(string t){
    type = t;
}

void setWidth(float w){
    width = w;
}

void setHeight(float h){
    height = h;
}

virtual float area() = 0;
virtual void display(){
    cout<<"Type : "<<type;
    cout<<"Width :"<<width;
    cout<<"Height :"<<height;
}
};


class rectangle:public shape{
public:
rectangle();
void display();
float area(){
    int A;
    A = width*height;
return A;
}
};



int main(){

rectangle rec;
rec.setHeight(4);
rec.setWidth(5);
rec.display();

}

它给出的错误:

04:36:04 **** Incremental Build of configuration Debug for project Q1 ****  

使所有 'Building file: ../src/Q1.cpp' 'Invoking: Cross G++ Compiler' g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/Q1.d" -MT"src/Q1.o" -o "src/Q1.o"
“../src/Q1.cpp” 'Finished building: ../src/Q1.cpp' ' ' 'Building target: Q1' 'Invoking: Cross G++ Linker' g++ -o "Q1" ./src/Q1.o
./src/Q1.o: 在函数 main' 中: F:\Semester 2\OOP\Theory\Assignment5-作文和InheritanceI-2167<br> D\Q1\Debug/../src/Q1.cpp:120: 未定义对 rectangle::rectangle()'
的引用 F:\Semester 2\OOP\Theory\Assignment5-作文和InheritanceI-2167
D\Q1\Debug/../src/Q1.cpp:123:
对矩形的 rectangle::display()' ./src/Q1.o:Q1.cpp:(.rdata$.refptr._ZTV9rectangle[.refptr._ZTV9rectangle]+0x0): undefined reference to vtable 的未定义引用' collect2.exe:错误:ld 返回了 1 个退出状态 make: *** [makefile:47: Q1] 错误 1 "make all" 以退出代码 2 终止。构建可能不完整。

04:36:06 Build Failed. 3 errors, 0 warnings. (took 2s.243ms)

继承和纯虚函数的存在都不是问题。

你会得到类似的错误
class rectangle {
public:
    rectangle();
    void display();
    float area(){
        int A = 42;
        return A;
    }
};


int main(){

    rectangle rec;
    rec.display();

}

您声明一个构造函数并声明一个方法 display,编译器将其视为您将在某处提供它们的定义的承诺。链接器找不到它们,因此出现错误。您必须定义这些方法。

然而,在您的代码中实际上这两种方法都不需要。您可以使用编译器生成的构造函数,您可以重用 shape::display,因此您可以将 rectangle 更改为:

class rectangle : public shape{
public:
    float area(){
        int A;
        A = width*height;
        return A;
    }
};