# Include <iostream> using namespace STD; Class A {public: A () {value ++; cout <"default a" <Endl;} A (const &) {value ++; cout <"const a" <Endl ;}a operator = (const A & A1) {cout <"operator =" <Endl; return A (A1);} void F () {cout <"value is" <value <Endl ;}~ A () {cout <"~ A "<Endl;} PRIVATE: static int value;}; int A: value = 0; void F1 (A A1) {a1.f (); cout <"f1" <Endl;} a F2 () {cout <"F2" <Endl; return a ();} void F3 () {A A1, a2; F1 (A1); a2 = F2 ();} int main () {F3 (); Return 0 ;}
The result is
Default A1 in a F3 calls Constructor
Default A2 in a F3 calls the constructor
The a variable in const a F1 calls the constructor with A1 as the parameter.
Value is 3 at this time there are three A objects, so the value is 3
F1 Print Output F1
~ The local variable in a F1 is out of the scope. At this time, the Destructor is called.
F2 F2 print out F2
Default a F2 calls the default constructor
Operator = F2 in F3, the output is printed only when the = Operator is called.
Const
~ A
~ A
~ A
~ A
This is actually a problem. Generally, * This (=, + =,-=, etc.) must be returned if a value is assigned)
Similar to the following
#include <iostream>using namespace std;class a{ public: a(){ value ++; cout <<"default a"<<endl; } a(const a&){ value ++; cout <<"const a"<<endl; } a& operator=(const a& a1){ cout <<"operator ="<<endl; return *this; } void f(){ cout <<"value is "<<value <<endl; } ~a(){ cout <<"~a"<<endl; } private: static int value;};int a::value = 0;void f1(a a1){ a1.f(); cout <<"f1"<<endl;}a f2(){ cout <<"f2"<<endl; return a();}void f3(){ a a1,a2; f1(a1); a2 = f2();}int main(){ f3(); return 0;}
4 class a{ 5 public: 6 a(int i):value(i){} 7 ~a(){cout <<"~a"<<endl;} 8 a& operator=(const a& a1){ 9 this->value = a1.value; 10 return *this; 11 } 12 int get(){return value;} 13 private: 14 int value; 15 };
The best method is =, + =,-=, and so on. These symbols cannot cause constructors,
Remember this time
A a1 = 10;
At this time, the constructor is called. Although the symbol = is used, this must be high-definition.
Result:
Default
Default
Const
Value is 3
F1
~ A
F2
Default
Operator =
~ A
~ A
~ A
Extremely important analysis