#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();
}
Dies ist der Code, den mein Professor mir gegeben hat, um C++ statischen Code zu üben.Wie wird diese Funktion aufgerufen, wenn ich dieses C++ - Programm ausführe?
Aber wenn ich dieses Programm ausführen, habe ich eine Frage.
Objekte zur Zeit lebendig: 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
Dies ist die Ausgabe. Aber ich weiß nicht, warum diese Funktion genannt wird Könnten Sie erklären?
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;
}
Und auch, warum static void gstats() {~} nach zerstörend foo # 2 genannt wird?
Es ist eine Kopie Konstruktor aufgerufen wird. Ihr Prof sollte wahrscheinlich mehr Zeit auf die Grundlagen verwendet haben, bevor Sie solchen unordentlichen Code auf Sie fallen lassen. – StoryTeller