我对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;
}
答案 0 :(得分:0)
这是在Windows GUI应用程序(具有WinMain
入口点的Windows应用程序)中吗?
如果是,则从命令行运行标准输出时不会自动显示。我不知道为什么会这样,但是IIRC正在运行:
myapp | cat
应该使标准输出正确设置。
答案 1 :(得分:0)
我无法重现这种行为。
#include<iostream>
struct FunkyNumber{
int m_intValue;
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;
}
void call(){
FunkyNumber num = 4;
FunkyNumber num2 = 6;
num += num2;
std::cout << num << std::endl; // This works okay!
// Should be destroyed here!
}
int main(int argc, char **argv){
call();
std::cout << "call ended" << std::endl;
}
这很好用。人们推广SSCCE的原因不仅在于帮助您更轻松地帮助您,还因为它可以帮助您找到问题所在的位置(显然不在您发布的代码中)。