C++ Effective_03

来源:互联网 发布:中拓互联 中文域名 编辑:程序博客网 时间:2024/05/01 18:02
char greeting[] = "Hello"; 


char* p = greeting; 


const char* p = greeting;
 
char* const p = greeting; 


const char* const p = greeting; 


void f1(const Widget* pw); 


void f2(Widget const * pw); 


std::vector<int> vec; 


const std::Vector<int>::iterator iter = vec.begin(); 
*iter = 10; 
++iter; //error


std::vector<int>::const_iterator cIter = vec.begin(); 
*cIter = 10; //error


class Rational {...}; 
const Rational operator* (const Rational& lhs, const Rational& rhs); 


class TextBlock {
public:
  const char& operator[] (std::size_t position) const 
  {
     return text[position]; 
  }
  
  char& operator[] (std::size_t position) 
  {
     return text[position]; 
  }
private:
  std::string text; 
}   




TextBlock tb("Hello");
std::cout << tb[0]; 


const TextBlock ctb("world"); 
std::cout << ctb[0]; 


void print(const TextBlock& ctb)
{
   std::cout << ctb[0]; 
}




class CTextBlock{
public: 
  char& operator[] (std::size_t position) const 
  {return pText[position]; }
private:
  char* pText; 
}
const CTextBlock cctb("Hello");
char* pc = &cctb[0]; 
*pc = 'J'; 


class CTextBlock{
public:
  std::size_t length() const; 
private:
  char* pText; 
  mutable std::size_t textLength; 
  mutable bool lengthIsValid;    
}; 


std::size_t CTextBlock::length() const 
{
  if(!lengthIsValid) {
     textLength = std::strlen(pText); 
     lengthIsValid = true; 
  }
  return textLength; 
}







0 0
原创粉丝点击