C++學習總結(下)

5.1 內聯函數

inline void show(){
	cout << "Hello Wordl!" <<endl;
}
int main(){
	show();
}
  • show()函數的內容複製到main函數中去

5.2 返回一個引用

int &sum(){
    int num = 1;
    int& rNum = num;
    return rNum;
}
int main(){
    int& ans = sum();
    cout << ans << endl;
    return 0;
}
  • 注意: 千萬不要返回局部對象的引用。當函數執行完畢時,將釋放分配給局部對象的存儲空間。此時,對局部對象的引用就會指向不確定的內存。

5.3 函數的重載

/* 重載決議1.不認識 &
 *         2.不認識 const
 */
// 重載: 函數名相同,參數不同;
void eating(int num);   //重載決議後的函數名字是:  eating_int
void eating(float num); //重載決議後的函數名字是:  eating_float

5.4 函數模板

//定義虛擬類型
template <typename T>//只在下面一個函數有效
void Swap(T &a,T &b){
    T temp = a;
    a = b;
    b = temp;
}
int main()
{
    double num1 = 4.7,num2 = 5;
    Swap(num1,num2);
    cout << num1 <<"  "<< num2 << endl;
    return 0;
}

6.面向對象

6.1基礎

class Student{
	private://私有屬性
		int values;
	public://共有屬性
		Student(){};    //構造函數
		~Student(){};   //析構函數
		void eat(); 	//函數的定義
};
//!!!一定要先寫出關係來
Student::Student() : values(15) { //簡單的賦值方法
	cout << "默認構造" << endl;
}
//類中函數方法的實現
Student::eat(){
	cout << "我是一個函數" << endl;	
}

最好定義在.hpp文件中去

6.2棧內存和堆內存

int main(){
	Student stu;						//在棧內存中定義一個對象
	Student* ptr_stu = new Student();	//在堆內存中定義一個對象
	
	delete ptr_stu;		//!!!在堆內存定義的東西使用完結束後一定要釋放堆內存
}

6.3 This指針

class Student{
	private://私有屬性
		int values;
	public://共有屬性
		Student(){};    //構造函數
		~Student(){};   //析構函數
		void eat(); 	//函數的定義
};
Student::Student(){
	this->values = 5; //This指針只能在對象中用,是函數的第一個隱式參數
	this->eat();  	  //通過This指針使用對象的方法
}

6.4運算符重載

class Integer{
    private:
        int m_value;
    public:
        //構造函數
        Integer() : m_value(0){}
        Integer(int value): m_value(value) {}
        //!!!重載運算符  實現兩個對象相加
        const Integer operator+(const Integer other)const;
        //得到值
        int getValue() {return m_value;}
        //析構函數
        ~Integer(){};
};

//實現運算符的重載
const Integer Integer::operator+(const Integer other)const {
    Integer result(this->m_value + other.m_value);
    return result;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章