c++基础要点(1-8点)

c++基础要点(1-8点)
//  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];
    }
    
     charoperator[]( 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;
}

你可能感兴趣的:(c++基础要点(1-8点))