作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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/
我是一名优秀的程序员,十分优秀!