【002】初識C++ 保留關鍵字(Typedef)、構造器和析構器

1.保留關鍵字  取別名(Typedef)

           


2.對象的創建

屬性+方法!

3.1定義構造器

       對於你自己寫的類,如果你沒有自己寫構造函數,編譯器會自動給你產生一個構造函數,讓你調用。

3.2 定義析構器

      析構器,也就是析構函數,當一個對象在消亡的時候,由編譯器自動調用。對於系統自帶的類型,例如int,char等,它的析構函數是由編譯器提供的,對於你自己定義的類,它的析構函數是你自己寫的。
      對象在什麼時候消亡呢?
       對於普通的對象來說,就是在離開它的作用域的時候,比如你在一個函數裏定義了一個對象,在跳出函數的時候,它就消亡了。

順帶說下new delete malloc free的區別,

int *p = new int();這個時候調用構造函數

delete p;這個時候調用析構函數

int *p = (int *)malloc(sizeof(int));這個時候不會調用構造函數

free(p);這個時候不會調用析構函數。


另外假如你定義一個類

class person{

public:

      person();

      persion(int age);

};


person myperson;這個時候會調用person();

person yourperson(10);這個時候會調用persion(int age);

代碼練習:

#include <iostream>
#include <string>
#include<fstream>

class StoreQuote
{
	public:
		std::string quote,speaker;
		std::ofstream fileOutput;
		
		StoreQuote();
		~StoreQuote();
		void inputQuote();
		void inputSpeaker();
		bool write();
		
};

StoreQuote::StoreQuote(){
	fileOutput.open("test.txt",std::ios::app); 
}

StoreQuote::~StoreQuote(){
	fileOutput.close();
}	
void StoreQuote::inputQuote(){
	std::getline(std::cin,quote);
}
void StoreQuote::inputSpeaker(){
	std::getline(std::cin,speaker);
}
bool StoreQuote::write(){
	if( fileOutput.is_open())
	{
		fileOutput<<quote<<"|"<<speaker<<"\n";
		return true;
	}else{
		return false;
	}

}		
			
int main(){
	StoreQuote quote;
	
	std::cout<<"請輸入一句名言:\n";
	quote.inputQuote();
	
	std::cout<<"請輸入作者:\n";
	quote.inputSpeaker();
	
	if( quote.write() ){
		 std::cout<<"寫入文件成功!\n";
	}	else{
		std::cout<<" 寫入文件失敗!\n";
		return 1;
	}
	
	return 0 ;
}







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章