gpt4 book ai didi

c++ - 当我运行这个 C++ 程序时,这个函数调用了什么?

转载 作者:行者123 更新时间:2023-11-30 05:06:50 28 4
gpt4 key购买 nike

#include <iostream>
using namespace std;


class foo
{
private:
static int cnt; // number in memory
static int nextid; // the next id number

public:
int id; // not shared - each object has it's own

foo()
{
cnt++; // update the counter of alive foos
id = nextid++; // assign an id
cout << "foo # " << id << " is alive " << endl;
}

~foo()
{
cnt--;
cout << "foo # " << id << " is dead " << endl;
}

void stats()
{
cout << "I am foo number " << id << endl;
gstats();
}

static void gstats()
{
cout << "Objects currently alive: " << cnt << endl;
cout << "Total number ever created: " << nextid << endl;
}

foo( foo &f)
{
cnt++; // update the counter of alive foos
id = nextid++; // assign an id
cout << "foo # " << id << " is alive and copied from " << f.id << endl;
}
};

int foo::cnt = 0;
int foo::nextid = 0;

void dmy1( foo a )
{
cout << "called dmy1 ( by value) id is " << a.id << endl;
}


void dmy2( foo &a)
{
cout << "called dmy2 (by reference) id is " << a.id << endl;
}

int main(void)
{
foo::gstats();

foo f1, f2;
f1.stats();

dmy1(f2);

foo::gstats();
}

这是我的教授给我的用于练习 C++ 静态代码的代码。

但是当我运行这个程序时,我有一个问题。

当前存活的对象:0

Total number ever created: 0
foo # 0 is alive
foo # 1 is alive
I am foo number 0
Objects currently alive: 2
Total number ever created: 2
foo # 2 is alive and copied from 1
called dmy1 ( by value) id is 2
foo # 2 is dead
Objects currently alive: 2
Total number ever created: 3
foo # 1 is dead
foo # 0 is dead

这是输出。但是我不知道这个函数为什么会被调用你能解释一下吗?

foo( foo &f)
{
cnt++; // update the counter of alive foos
id = nextid++; // assign an id
cout << "foo # " << id << " is alive and copied from " << f.id << endl;
}

还有,为什么在析构 foo #2 之后调用 static void gstats(){ ~ }?

最佳答案

好的,我试着解释发生了什么

首先显示此时不存在对象

foo::gstats();

现在 f1 和 f2 在堆栈上声明和创建(2 个对象存活)

foo f1, f2;

f1.stats 被调用并显示当前状态

f1.stats();

f2 按值传递(通过复制构造函数调用 foo( foo &f) 在堆栈上复制)到 dmy1(3 个对象存活)

dmy1(f2);

离开 dmy1 后,它的作用域(它使用的堆栈变量)被销毁,f2 的拷贝调用它的析构函数(2 个对象存活)并显示此状态

foo::gstats();

然后 main() 被留下,它的作用域也被销毁,f1 和 f2 的析构函数被调用(0 个对象存活)

关于c++ - 当我运行这个 C++ 程序时,这个函数调用了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47748154/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com