using namespace std;
The class Person {
Public:
The Person (s)
{
Cout & lt; & lt; "Person, no arguments constructor calls" & lt; & lt; endl;
}
The Person (int a, int height)
{
Age=a;
M_height=& amp; Height;
Cout & lt; & lt; "The Person have arguments constructor calls" & lt; & lt; endl;
}
The Person (const Person & amp; P)
{
Age=p.age;
M_height=p. _height;
Cout & lt; & lt; "Person's copy constructor calls" & lt; & lt; endl;
}
To the Person (s)
{
Cout & lt; & lt; "Person's destructor call" & lt; & lt; endl;
}
int age;
Int * m_height;
};
Void test ()
{
The Person p1 (18172);
The Person p2 (p1);
Cout & lt; & lt; P2. Age<& lt;" "<& lt; * the p2 m_height & lt; & lt; endl;
}
Int main ()
{
The test ();
system("pause");
return 0;
}
Why * p2 m_height output is garbled, I is the height of the inside address to the pointer m_height ah
CodePudding user response:
Call you when we have arguments constructor m_height point to an a stack object, in and after the constructor is goneCodePudding user response:
Is that you get the address, complete with the end of the function and the parameters, the structure function after the operation, they don't have a natural is a random numberCodePudding user response:
The Person (int a, int height){
Age=a;
M_height=& amp; Height;
Cout & lt; & lt; "The Person have arguments constructor calls" & lt; & lt; endl;
}
The function, int height is a temporary object, the height of the life cycle, at the end of this function at the end of the stack space are recycled, here m_height=& amp; Height; After the end of this function call, m_height will become a wild pointer,
CodePudding user response:
There are and the constructor:This
M_height=& amp; Height;
To:
M_height=height;
The test function
This statement:
Cout & lt; & lt; P2. Age<& lt;" "<& lt; * the p2 m_height & lt; & lt; endl;
Instead of
Cout & lt; & lt; P2. Age<& lt;" "<& lt; P2. M_height & lt; & lt; endl;
It's good
CodePudding user response:
The Person (int a, int height){
Age=a;
M_height=& amp; Height;//this height is a local variable, m_height point to the address of the local variable, left the function, the local variable disappears, m_height became wild pointer, this is a common mistake pointer usage that LZ usage is not enough understanding of general pointer
Cout & lt; & lt; "The Person have arguments constructor calls" & lt; & lt; endl;
}