【问题标题】:CPP, Variables don't go out of scopeCPP,变量不会超出范围
【发布时间】: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


【解决方案1】:

在你的代码中你有注释的地方

//should print out "deleting" here 
//because of a going out of scope

“a”没有超出范围。随着应用程序终止,它将超出范围。其他类似问题 (Are destructors run when calling exit()?) 讨论了应用程序终止时您可以期待什么。

【讨论】:

    猜你喜欢
    • 2016-04-30
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2020-12-24
    • 2013-10-26
    • 2016-01-09
    相关资源
    最近更新 更多