简体   繁体   English

我无法理解析构函数有什么问题?

[英]I can't understand what is wrong with the destructors?

I have a class called polygon which is my base class in which I have area and perimeter and I need to derive a rectangle class from it. 我有一个名为polygon的类,它是我的基类,我有区域和周长,我需要从中派生一个矩形类。 Right now the program below doesn't work work and it gives me the following error: 现在,下面的程序无法正常工作,它给我以下错误:

GS_Inheritance_Program.obj : error LNK2019: unresolved external symbol "public: virtual
 __thiscall rectangle::~rectangle(void)" (??1rectangle@@UAE@XZ) referenced in function 
"public: virtual void * __thiscall rectangle::`scalar deleting destructor'(unsigned int)" 
(??_Grectangle@@UAEPAXI@Z)

It is due to destructors that I added to the program but when I remove them both it works. 这是由于我添加到程序中的析构函数,但当我删除它们时它都有效。 I did some research and found out that it might be due to me not compiling the program .cpp file correctly. 我做了一些研究,发现可能是因为我没有正确编译程序.cpp文件。 Is that my problem? 那是我的问题吗? If not, what is my problem? 如果没有,我的问题是什么?

#include <iostream>
using namespace std;

class polygon
{
protected:
    double area;
    double perimeter;

public:
    polygon(){}
    ~polygon();
    double printperimeter();
    double printarea();
};

double polygon::printperimeter()
{
    return perimeter;
}

double polygon::printarea()
{
    return area;
}

class rectangle:public polygon
{
protected:
    double length;
    double width;
public:
    rectangle(double = 1.0, double = 1.0);
    ~rectangle();
    double calcarea();
    double calcperimeter();
};

rectangle::rectangle(double l, double w)
{
    length = l;
    width = w;
}

double rectangle::calcarea()
{
    area = length*width;
    return printarea();
}

double rectangle::calcperimeter()
{
    perimeter = 2*(length+width);
    return printperimeter();
}

void main()
{
    rectangle rect_1 (9.0, 5.0);

    cout<<"The Area of Rect_1 is " <<rect_1.calcarea() <<endl;

    system("pause");
}

You declared destructors in your classes. 你在课堂上宣布了析构函数。 But you never defined them. 但你从未定义过它们。 Why would you declare functions and then fail to define them? 为什么要声明函数然后无法定义它们? You declared polygon::~polygon() and rectangle::~rectangle() . 你声明了polygon::~polygon()rectangle::~rectangle() Neither is defined though. 但两者都没有定义。

You are basically lying to the compiler. 你基本上是骗了编译器。 You make a promise by declaring a function, and then you break that promise by failing to define it. 你通过声明一个函数来做出承诺,然后通过不能定义它来打破这个承诺。 Hence the error. 因此错误。

PS And that's int main() , not void main() . PS那是int main() ,而不是void main()

You didn't add destructors. 你没有添加析构函数。 You said you added them, but you didn't actually add them. 你说你添加了它们,但实际上并没有添加它们。 So the linker is looking for them and not finding them. 所以链接器正在寻找它们而不是找到它们。

You could just change: 你可以改变:

            ~rectangle();

to

            ~rectangle() { ; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM