- declaration and definition
Any variable can be defined for only once. On the contrary, declaration is different. Extern declaration is not definition and does not allocate memory for the variable.
2. cin and getline
getline ignore space, so in case I wanna input something like space inside my string, getline is for sure a better choice.
3. something about vector
Vector is a useful class template, in order to use it, we need to include certain headfiles. Actually, to ensure we can have a continuous piece of memory, we tend to create an empty vector first, can increase its element dynamically.
4. about constructor
1: #include <iostream>
2: using namespace std;
3: class Complex{
4: double real;
5: double imag;
6: public:
7: //無參建構函式
8: Complex(void)
9: {
10: real = 0.0;
11: imag = 0.0;
12: cout<<"Constructor with no parameter gets called!"<<endl;
13: }
14: //一般建構函式
15: Complex(double r, double i)
16: {
17: real = r;
18: imag = i;
19: cout<<"Normal constructor gets called!"<<endl;
20: }
21: //複製建構函式
22: Complex(const Complex &s)
23: {
24: real = s.real;
25: imag = s.imag;
26: cout<<"Copy constructor gets called!"<<endl;
27: }
28: //類型轉換建構函式
29: Complex(double r)
30: {
31: real = r;
32: imag = 0.0;
33: cout<<"Type transform constructor gets called!"<<endl;
34: }
35: //等號運算子多載
36: Complex& operator=(const Complex &s)
37: {
38: cout<<"Equality operator overload!"<<endl;
39: if(this == &s)
40: {
41: return *this;
42: }
43: this->real = s.real;
44: this->imag = s.imag;
45: return *this;
46: }
47: };
48: int main()
49: {
50: Complex a,b; //constructor with no parameter
51: Complex c(1.2,3.4); //normal constructor
52: Complex d = Complex(1.2,3.4); //normal constructor
53: Complex e = c; //copy constructor
54: a = c; //a is already constructed, = operator overload
55: b = 5.2; //type transform constructor
56: Complex f(c); //copy constructor
57:
58: }
this little piece of code outputs:
Constructor with no parameter gets called!
Constructor with no parameter gets called!
Normal constructor gets called!
Normal constructor gets called!
Copy constructor gets called!
Equality operator overload!
Type transform constructor gets called!
Equality operator overload!
Copy constructor gets called!
請按任意鍵繼續. . .
Complex test1(const Complex& c)
{
return c;
}
Complex test2(const Complex c)
{
return c;
}
Complex test3()
{
static Complex c(1.0,5.0);
return c;
}
Complex& test4()
{
static Complex c(1.0,5.0);
return c;
}
int main()
{
Complex a,b; //constructor with no parameter
//Complex c(1.2,3.4); //normal constructor
//Complex d = Complex(1.2,3.4); //normal constructor
//Complex e = c; //copy constructor
//a = c; //a is already constructed, = operator overload
//b = 5.2; //type transform constructor
//Complex f(c); //copy constructor
//// 下面函數執行過程中各會調用幾次建構函式,調用的是什麼建構函式?
test1(a); //copy copy
test2(a); //copy
b = test3(); //normal copy = overload
b = test4(); //normal overload
test2(1.2); //type transform, copy
// 下面這條語句會出錯嗎?
test1(1.2);
test1( Complex(1.2 ));