为什么这个C++程序即使不构造类对象也能成功运行?让我们看看下面的代码:
#include<iostream>
using namespace std;
class Dopey
{
public:
Dopey() {cout << "Dopey\n";}
};
class Bashful
{
public:
Bashful() { cout << "BashFul\n";}
void f() { cout << " f \n";}
int i;
};
class Sneezy
{
public:
Sneezy(int i) {cout << "copy int \n";}
Sneezy(Bashful d) { cout << "copy Bashful\n";}
Sneezy(Bashful* d) {d->f();d->i=100;} //How could this be correct without
// constructing d !!!!!!!!
Sneezy();
};
class Snow_White
{
public:
Snow_White();
Dopey dopey;
Sneezy sneezy;
Bashful bashful;
private:
int mumble;
};
Snow_White::Snow_White() : sneezy(&bashful)
{
mumble = 2048;
}
int main()
{
Snow_White s;
return 0;
}
该程序可以成功运行,cout如下:
Dopey
f
BashFul
看看without constructing bashful,the f() could be invoked
,为什么?当我将功能更改Snow_White::Snow_White()
为以下内容时:
Snow_White::Snow_White() : sneezy(bashful)
{
mumble = 2048;
}
它也runs successfully without constructing bashful
,cout如下:
Dopey
copy Bashful
Bashful
任何解释将不胜感激!谢谢 !