C++學習(1)

<!-- @page { size: 21cm 29.7cm; margin: 2cm } PRE.western { font-family: "Courier New", monospace } PRE.cjk { font-family: "新宋體", monospace } PRE.ctl { font-family: "新宋體", monospace } P { margin-bottom: 0.21cm } -->

關於構造函數
   創建一個類類型的對象時,編譯器會自動使用一個構造函數來初始化該對象。
   構造函數的儘量初始化數據而不是對數據賦值。
 Person(const string &na,const string &add):name(na),address(add){}

	//
初始化
Person(const string &na,const string &add){

name=na;

address=add;

}//
初始化+
賦值 多了1
布

重載操作符
 = +=
要返回自身的一個引用 用於連鎖賦值
a=c=b=10;


Person& operator=(Person& p)

	{

		name+=p.getPersonName();

		address+=p.getPersonAddress();

		return *this;

	};1C++Person.h

#ifndef __PERSON__

#define __PERSON__

#include <string>

#include <iostream>

using namespace::std;

class Person{

public:

	Person(const string &na,const string &add);

	~Person();

	string getPersonName() const;

	string getPersonAddress() const;

	Person& operator=(Person& p);

	

private:

	string name;

	string address;





};

inline string Person::getPersonName() const

{

	

	return name;

}

inline string Person::getPersonAddress() const

{

	return address;

}

#endif


Person.cpp

#include "Person.h"


Person::Person(const string &na,const string &add):name(na),address(add){


}

Person::~Person()

{

	cout<<"free"<<endl;

}

Person& Person::operator =(Person& p){

	name+=p.getPersonName();

	address+=p.getPersonAddress();

	return *this;

};


類的定義與聲明:
類聲明給出了1
個不完全的類型 只能定義指向該類型的指針或引用。
如果要創建類的對象以及時候指針或引用訪問類的成員,必須先定義!


class y;


class x{

public :

	y *p;

     void f(y t);


};

class y{

public :

	x p;

};


錯誤的
class x;

class y{

public :

	x p;

};


class x{

public :

	y *p;


};



const 
對象只能使用const
成員
要不確定的話 可以重載const
成員函數
const Screen& display(ostream &os) const;//const
對象只能調用這個
	Screen& display(ostream &os) ;



explicit 
防止構造函數隱式轉換


explicit Person(const string &na,const string &add="");


	

	~Person();

	bool isSame(const Person &p){

		return false;

	}


string nullbuul="te";

		

cout<<p2.isSame(nullbuul)<<endl; //error
發佈了4 篇原創文章 · 獲贊 1 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章