1. Constant -- use a constant in a class
[Cpp]
# Include <iostream>
Using namespace std;
Class
{
Private:
Const int SIZE = 18;
Public:
A (){}
};
Int main ()
{
Return 0;
}
# Include <iostream>
Using namespace std;
Class
{
Private:
Const int SIZE = 18;
Public:
A (){}
};
Int main ()
{
Return 0;
} The above program encountered an error during compilation. The member variables defined in the const class can only be initialized in the constructor.
[Cpp]
# Include <iostream>
Using namespace std;
Class
{
Private:
Const int SIZE;
Public:
A (int size): SIZE (size ){}
// The constant variable can only be in the constructor, And the SIZE cannot be set in common methods.
// Compilation failed
Void setSize (int size)
{
SIZE = size;
}
};
# Include <iostream>
Using namespace std;
Class
{
Private:
Const int SIZE;
Public:
A (int size): SIZE (size ){}
// The constant variable can only be in the constructor, And the SIZE cannot be set in common methods.
// Compilation failed
Void setSize (int size)
{
SIZE = size;
}
}; 2. function return value
[Cpp]
# Include <iostream>
Using namespace std;
Char * getStr ()
{
Char p [] = "abc ";
Return p;
}
Int main ()
{
Char * t = NULL;
T = getStr ();
// Output garbled characters
Cout <t <endl;
Return 0;
}
# Include <iostream>
Using namespace std;
Char * getStr ()
{
Char p [] = "abc ";
Return p;
}
Int main ()
{
Char * t = NULL;
T = getStr ();
// Output garbled characters
Cout <t <endl;
Return 0;
} A local character array is defined in getStr (), which stores the string "abc ". Returns the first address of p. The output result is garbled. Because p is defined in getStr (), local variables are allocated in the stack area of the memory, which is used inside the function body. After the function body ends, the stack zone is automatically released. So garbled characters are output in the main function.
[Cpp]
# Include <iostream>
Using namespace std;
Char * getStr ()
{
Char p [] = "abc ";
P address in printf ("getStr (): % d \ n", p );
Return p;
}
Int main ()
{
Char * t = NULL;
Printf ("t initial address: % d \ n", t );
T = getStr ();
Printf ("t address after function call: % d \ n", t );
Return 0;
}
# Include <iostream>
Using namespace std;
Char * getStr ()
{
Char p [] = "abc ";
P address in printf ("getStr (): % d \ n", p );
Return p;
}
Int main ()
{
Char * t = NULL;
Printf ("t initial address: % d \ n", t );
T = getStr ();
Printf ("t address after function call: % d \ n", t );
Return 0;
}
In the preceding procedure, t and p point to the same address. However, the getStr () variable scope is only in the function body. Therefore, in the main function, the output content of the same address as p is garbled.
[Cpp]
<PRE> </PRE>
<PRE> </PRE>
<PRE> </PRE>