C++ 基礎 二 靜態,單列,this 模板 友元 類型轉換

1.靜態成員變量,函數

class Person {
public:
	static int age;            };

int main(void) {
	Person p;
	p.age;
	Person::age;        }

    1. 使用創建對象的方式訪問,        2. 直接使用類訪問,   3.靜態成員函數 不能訪問普通變量, 4.普通函數可以訪問靜態

2.單例模式

1.將類的構造函數和拷貝函數以及成員變量都設置爲私有,   2.然後外部通過共有的靜態方法來獲取 Printer*的指針  

3.靜態成員變量最好在類的外部初始化 雖然是singlePrinter私有的但是加上Printer::依然是在類內

class Printer {
private:
	static Printer* singlePrinter;

private:
	Printer() {};
	Printer(const Printer& p) {};
public:
	static Printer* getInstance() {

		return singlePrinter;
	}
};
Printer* Printer::singlePrinter = new Printer;

3.this 是一個指針 誰調用就指向誰, *this代表對象本身   非靜態成員纔有

4.常函數,對象

    必須是類中的函數,在後面加上  const  ,表示不允許修改 this指針 指向的值      相當於  const  Person * const this 

class Printer {
	void test() const
	{                }}

   1.const Person p  修飾的對象  不能再   p.age =100;   修改       2.常對象只能調用 成員常函數

5.友元函數

  本來 test是類的私有方法,  所以test2不能訪問, 但是在類中聲明  友元函數 就可以訪問了

class Printer {
	friend void test();
private:
	void test()
	{}                    };

void test2()
{
	Printer p;
	p.test();
}

6.各種重載

7.函數模板

1. 這樣 函數 就可以傳入兩個類型一樣的任意類型了      2.如果普通的與模板函數重載,  先調用普通的   3.繼承時告訴T的類型

template<class T>
void mySwap(T &a,T &b)
{	}

2.具體 模板

template<> bool test<Person>(Person &a, Person &b){}

3.類模板      ,分文件編寫時,需要導入 .cpp而不是 .h       所以在寫模板時,      把.cpp和.h寫在一個文件    命名爲 .hpp


template<class NameType ,class AgeType>
class Person
{
	Person(NameType n,AgeType a) {};
};
Person<string, int> p("wyc", 15);

8.靜態, 動態類型轉換,常量轉換

   1.對於 父類 與 子類也 也可以使用這種轉換

int main(void) {
	char a = 'a';
	double b =static_cast<double>(a);
	cout << b << endl;        }   97

  2.動態  dynamic_cast

   不能轉換基本數據類型,  只能轉換父類子類這種, 父轉子不可以 ,  子轉父 可以    發生多態可以

  3.常量轉換

   去掉const  或增加const 都可以 , 只能對指針或者應用類型的 數據進行轉換

const int* m = NULL;
int* n = const_cast<int*>(m);

 

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