在我的代碼中,我不明白爲什麼我的派生類對象沒有被銷燬,即使我明確調用了析構函數。我不知道它是否因爲我沒有包括刪除或與範圍有關,但你能幫我嗎?我在我的代碼添加了註釋,以幫助說明我的問題爲什麼我的析構函數不會銷燬我的對象,它仍然保留其成員變量值?
在我的頭文件我有:
#ifndef test_test_h
#define test_test_h
#include <iostream>
#include <string>
using namespace std;
class test{
public:
test();
void setName();
string getName();
private:
string name;
};
class book:public test{
public:
book();
~book();
void setBook();
string getBook();
private:
string bookName;
};
#endif
我在執行文件我有:
#include "test.h"
test::test()
{
cout<<"calling base construtor"<<endl;
name="hi";
}
book::book()
{
cout<<"Calling derived constructor"<<endl;
bookName="yolo";
}
test::~test()
{
cout<<"calling test destructor"<<endl;
}
book::~book()
{
cout<<"calling book destructor"<<endl;
}
void test::setName()
{
cout<<"Input name"<<endl;
cin>>name;
}
string test::getName()
{
return name;
}
void book::setBook()
{
cout<<"Input name"<<endl;
cin>>bookName;
}
string book::getBook()
{
return bookName;
}
在我的主文件我有:
#include "test.h"
int main(){
book b;
b.setBook();
cout<<b.getBook()<<endl;//takes user input
cout<<b.getBook()<<endl;//displays the input u put in
b.~book();
cout<<b.getBook()<<endl;//for some reason it still prints out whatever you inputed even though I called the destructor earlier. I would think it would display yolo because that string is saved in the constructor of book
}
不要直接打電話給dtor。它在對象被刪除時自動調用。這是你釋放對象所擁有的任何內存的地方。 – twentylemon
@twentylemon這沒有回答我的問題哈哈。我的析構函數應該仍然刪除我的對象,但它沒有 – user5007232
不,它不應該刪除對象。 'b'仍然在範圍內。你所做的只是調用名爲'〜book'的函數。 – twentylemon