gpt4 book ai didi

c++ - 使用析构函数后,代码显示 "reference to Book::~Book()"错误

转载 作者:行者123 更新时间:2023-11-30 02:35:13 26 4
gpt4 key购买 nike

我是 C++ 的学习者,我对构造函数和析构函数感兴趣。我编译了下面的代码,它返回了对 Book::~Book() 错误的 undefined reference 。但是当我注释掉析构函数时,它工作正常。我想我可以在使用析构函数后创建成员函数。我在这里做错了什么?为了更好地理解,我在下面编写了我的代码

class Book
{
private:
int *pages;
int *price;

public:
Book() //default constructor
{
pages = new int;
price = new int;
*pages = 300;
*price = 8;
};

void pre_destructor()
{
std::cout << "The pages:" << *pages;
std::cout << "The price:" << *price;
}

~Book(); //destructor

void post_destructor()
{
std::cout << "The pages:" << *pages << "\n";
std::cout << "The price:" << *price << "\n";
delete pages;
delete price;
}
};

int main()
{
using namespace std;
Book book1;

cout << "Before using destructors" << endl;
cout << "---------------------------------"<< endl;

book1.pre_destructor();

cout << "After using destructors" << endl;
cout << "---------------------------------";

book1.post_destructor();

return 0;
} //destructor is called here

最佳答案

我已经缩短了一点。之前的 void pre_destructor() 毫无意义;最好放在 dtor(“析构函数”的缩写)本身中,post_destructor() 甚至可能有害。

#include <iostream>

class Book
{
private:
int *pages;
int *price;

public:
Book() : pages(new int(300)), price(new int(8)) {}

~Book() {
std::cout << "The pages:" << *pages << "\n";
std::cout << "The price:" << *price << "\n";
delete price;
delete pages;
}
};

int main()
{
{
Book book1;
} //destructor is called here

return 0;
}

live在 Coliru 的

关于c++ - 使用析构函数后,代码显示 "reference to Book::~Book()"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33839428/

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