gpt4 book ai didi

c++ - 我不明白析构函数有什么问题?

转载 作者:行者123 更新时间:2023-11-28 03:26:12 26 4
gpt4 key购买 nike

我有一个名为多边形的类,它是我的基类,其中我有面积和周长,我需要从中派生一个矩形类。现在下面的程序不起作用,它给了我以下错误:

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)

这是由于我添加到程序中的析构函数,但是当我删除它们时它们都起作用了。我做了一些研究,发现这可能是因为我没有正确编译程序 .cpp 文件。那是我的问题吗?如果不是,我的问题是什么?

#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");
}

最佳答案

您在类中声明了析构函数。但你从未定义过它们。为什么你会声明函数然后却无法定义它们?您声明了 polygon::~polygon()rectangle::~rectangle()。但是两者都没有定义。

你基本上是在欺骗编译器。你通过声明一个函数来做出 promise ,然后你又因为没有定义它而违背了这个 promise 。因此错误。

附言那是 int main(),而不是 void main()

关于c++ - 我不明白析构函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13888414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com