我是C++的学习者,我对构造函数和析构函数的主题很感兴趣。我编译了下面的代码,它返回了对Book::~Book()错误的未定义引用。但是当我注释掉析构函数时,它工作得很好。我想我可以在使用析构函数之后创建成员函数。我在这里做错了什么?为了更好的理解,我写了下面的代码。
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发布于 2015-11-21 11:57:17
我已经把它缩短了一点。以前的析构函数是没有意义的;最好放在void pre_destructor() (“析构函数”的缩写)本身中,而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;
} Coliru's的
发布于 2015-11-21 11:40:57
您的析构函数已声明,但从未定义。
看起来"post_destructor“做了实际的破坏。因此,您需要做的就是编写析构函数,如下所示:
~Book() {} // empty, nothing to do here...https://stackoverflow.com/questions/33839428
复制相似问题