注册 登录
编程论坛 C++教室

新人!!问问

shiyuedef 发布于 2011-05-28 10:12, 394 次点击
#include <iostream.h>
class sample
{
public:
sample()
{cout<<”hello”<<endl;}
};
void fn(int i)
{static sample c;
cout<<”j=”<<i<<endl;
}
void main()
{fn(20);
fn(30);
}
hello
j=20
j=30
结果为什么是这个呢?怎么一个hello的
5 回复
#2
wavewind2011-05-28 10:34
#include <iostream.h>
class sample
{
public:
sample()
{cout<<”hello”<<endl;}  //这是一个构造函数
};
void fn(int i)
{static sample c;        //这里建立了一个类对象,建立类对象的时候系统自动调用上面
                         //的构造函数,这个也就是为什么输出中有个hello的原因
cout<<”j=”<<i<<endl;
}
void main()
{fn(20);
fn(30);
}
#3
lianjiecuowu2011-05-28 12:41
#include <iostream>
using namespace std;
class sample
{public:
    sample(){cout<<"hello"<<endl;}

};
void fn(int i)
{static sample c;     //构造静态对象,在主函数中,要调用构造函数,因此会输出hello,然后执行fn()函数,输出j的值
cout<<"j="<<i<<endl;

}
int  main()
{fn(20);
fn(30);
system("pause");
return 0;
}
#4
donggegege2011-05-28 13:52
不错
#5
shiyuedef2011-05-28 22:29
我想问为什么输出1个hello而不是2个?不是用了2次fn()吗
#6
寂寞的灵魂2011-05-29 13:32
因为你定义的对象c为static(静态的),静态变量只定义一次,也就是说你调用fn(30)时根本没有新对象生成,那么自然不会输出hello了;
可这样验证:
#include <iostream.h>

class sample
{
public:
    sample()
    {
        i=0;    //初始化i=0;
        cout<<"hello"<<endl;
    }
    void Add(){i++;cout<<"i="<<i<<endl;}    //i自增1,并输出;
private:
    int i;   
};
void fn(int i)
{
    static sample c;
    c.Add ();    //调用Add();
    cout<<"j="<<i<<endl;
}
void main()
{
    fn(20);
    fn(30);
}
结果:
hello
i=1
j=20
i=2    //若生成新对象,则此处i应为1!!
j=30
表明两次都是对同一对象中的i操作,若去掉static关键子则有两个hello输出;
1