• 一个变量只能调用一次构造函数,那就是在定义变量的时候调用,除非变量为局部变量,否则不会重复调用,一直到程序结束也就调用那么一次。也就是说只有在定义新的变量的时候才会调用构造函数。 【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");
   
 }
   
 
 

 运行结果: