构造函数的调用时机/次数

来源:互联网 发布:300533冰川网络 编辑:程序博客网 时间:2024/05/17 01:59
  • 一个变量只能调用一次构造函数,那就是在定义变量的时候调用,除非变量为局部变量,否则不会重复调用,一直到程序结束也就调用那么一次。也就是说只有在定义新的变量的时候才会调用构造函数。
    【eg1】定义在主函数的情况
    #include<iostream>
    #include<windows.h>
    using namespace std;


    class A
    {
    public:
    A();
    int a;
    int b;
    int c;
    };


    A::A()
    {
    system("Color 6f");
    cout << "调用构造函数" << endl;
    }
    int main()
    {
    A testt;
    cout<<"djfai"<<endl;
    testt.a = 1;
    testt.b = 3;
    testt.c = 4;
    if (testt.c > 0)
    testt.a = 3;
    A FA;
    FA.a = 3;
    system("pause");
    }


  • 运行结果:


  • 【eg2】变量为局部变量

  • #include<iostream>


    using namespace std;


    class A
    {
    public:
    A();
    int a;
    int b;
    int c;
    };


    A::A()
    {
    cout << "调用构造函数" << endl;
    }


    void fun()
    {
    A aa;
    aa.a = 1;
    aa.b = 2;
    aa.c = 3;
    }
    int main()
    {
    system("Color 6f");
    fun();
    fun();
    fun();
    system("pause");
    }

运行结果:

0 0
原创粉丝点击