我对 C++ 很陌生,但我认为我说得对,在堆栈上声明的对象应该在超出范围时自动被破坏/销毁?在我目前正在使用的迷你项目中,情况并非如此。
void MainWindow::clickTest() {
FunkyNumber num = 4;
FunkyNumber num2 = 6;
num += num2;
std::cout << num << std::endl; // This works okay!
// Should be destroyed here!
}
我的析构函数应该这样做:
virtual FunkyNumber::~FunkyNumber() {
std::cout << "goodbye cruel world! (" << m_intValue << ")" << std::endl;
// m_intValue is just the int value of this "FunkyNumber"
}
但是没有任何东西成为标准!
可能应该提到我正在使用 Qt - 但这只是一个普通的 C++ 类,所以从我能说的来看这并不重要......
编辑:funkynumber.cpp:
#include "funkynumber.h"
FunkyNumber::FunkyNumber(int num)
: m_intValue(num) {
std::cout << "made a funkynumber " << num << std::endl;
}
FunkyNumber::~FunkyNumber() {
std::cout << "goodbye cruel world! (" << m_intValue << ")" << std::endl;
}
int FunkyNumber::intValue() const {
return m_intValue;
}
void FunkyNumber::operator+=(const FunkyNumber &other) {
m_intValue += other.intValue();
}
void FunkyNumber::operator=(const FunkyNumber &other) {
m_intValue = other.intValue();
}
bool FunkyNumber::operator==(const FunkyNumber &other) {
return other.intValue() == m_intValue;
}
std::ostream &operator<<(std::ostream &outStream, const FunkyNumber &num) {
outStream << "FunkyNumber (" << num.intValue() << ")";
return outStream;
}