【发布时间】:2016-05-12 03:24:53
【问题描述】:
在我所做的所有其他实验中,我的变量都超出了预期的范围,但是当我将变量放在 main 方法中时,它们并没有超出范围,或者看起来就是这样,因为析构函数永远不会得到叫:
#include <string>
#include <iostream>
using namespace std;
#define PRINT(s) cout << s
#define PRINTLN(s) PRINT(s) << endl
class Animal
{
public:
string name;
int legs;
Animal(string name, int legs) {
this->name = name;
this->legs = legs;
}
~Animal(){
PRINTLN("deleting");
}
static Animal createAnimal() {
PRINTLN("creating");
return Animal("animal", 4);
}
};
int main() {
PRINTLN("start");
Animal a = Animal::createAnimal();//or Animal a("hello", 5);
PRINTLN("end running method");
PRINTLN("end");
system("pause");
return 0;
//should print out "deleting" here
//because of a going out of scope
}
【问题讨论】:
-
返回后应该打印删除。从命令行运行您的程序以查看它。或按 ctrl-f5 在 Visual Studio 上不调试即可运行。
-
includes 在哪里? -
这就是问题所在,根本没有打印删除
-
我假设您在 Visual Studio 上,并且在返回窗口关闭窗口后,您没有看到结果。这就是为什么我给了你两种方法来解决这个问题。
-
#include
和 #include
标签: c++ memory scope destructor