// testss.cpp : 定義控制臺應用程序的入口點。
//
#include "stdafx.h"
#include <string>
using namespace std;
char& testfun(char &m)
{
return m;
}
class CTextBlock
{
public:
int length() const;
const char &operator[](int pos) const
{
//其他代碼
return pText[pos];
}
char& operator[](int pos)
{
return const_cast<char&>( static_cast<const CTextBlock>(*this)[pos] );
}
private:
char *pText;
mutable int textLength; //
mutable bool lengthIsValid;
};
int CTextBlock::length() const
{
if(!lengthIsValid)
{
textLength = strlen(pText);
lengthIsValid = true;
}
return textLength;
}
template<class T>
class NameObject{
public:
NameObject(string &name,const T&value):nameValue(name),objectValue(value)
{
}
private:
std::string &nameValue;
const T objectValue;
};
int _tmain(int argc, _TCHAR* argv[])
{
//1.const位置使用
//以下a1,a2等同
const int a1 = 10;
int const a2=10;
//以下b1,b2等同
int const *b1 = NULL;
const int *b2 = NULL;
//指針c不允許改變
int * const c = NULL;
//2.返回引用問題
//必需返回char &,否則返回char則不能被賦值
char m = 'a';
testfun(m) = 'p';
//3.mutable(可變的)
const CTextBlock textBlock;
//在length中用mutable修飾textLength和lengthIsValid,
//所以const函數length才可以訪問非const成員變量
textBlock.length();
//4.調用非const[]時,調用const類型的[]重載
//詳細請參見[]重載
const char& pChar=textBlock[0];
CTextBlock textBlock2;
char& tChar = textBlock2[0];
//5.類的成員,盡可能的使用初始化列表一一初始化,
//比賦值效率更高,也可以預防不明確行為的潘多拉盒子
//父類比子類先初始化,類成員初始化順序是按變量聲明的順序,
//即使初始化成員列表用其他順序。
//6.為避免“跨編譯單元之初始化次序”問題,請以local static對象替換
//non-local的static對象(local static即函數內的,其他的稱為non-local static)
//例如,單件返回static 對象引用的方法
//7.編譯器自動生成構造函數,拷貝構造,=運算符重載,非virtual的析構函數。
//如果有編寫構造函數時,編譯器不會自動生成默認構造和拷貝構造函數。同樣定義
//拷貝構造也不會生成默認構造函數,但會生成=,析構函數( 但在有被使用的時候才會生成)
//8.編譯器自動生成“=”運算符重載時的特殊問題
string newDog("persephone");
string oldDog("stach");
NameObject<int> p(newDog,2);
NameObject<int> s(oldDog,36);
//以下這種情況編譯器是不會自動生成賦值“=”構造的,原因是
//在一個內含引用成員的或const成員時,編譯器不知道如何自動生成
//賦值函數內的實現。還有一種情況是,如果將父類"="函數定義為private
//編譯器同樣在子類中不會自動生成賦值函數。
p = s;//該行語法錯誤
return 0;
}