C++ Primer Plus学习:第十二章 类和动态内存(2)

本文详细介绍了C++中字符串类的实现细节,包括构造函数、运算符重载、静态函数等,并通过实例展示了如何在程序中使用这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

eg

  string1.h

#include <iostream>
using std::ostream;
using std::istream;

#ifndef STRING1_H_
#define STRING1_H_
class String
{
      private:
              char * str;
              int len;
              static int num_strings;
              static const int CINLIM = 80;
      public:
             String(const char *s);
             String();
             String(const String&);
             ~String();
             int length()const{return len;}
             //overloaded operator methods
             String & operator=(const String &);
             String & operator=(const char *);
             char & operator[](int i);
             const char & operator[](int i)const;
             //overloaded opeartor friends
             friend bool operator<(const String &st,const String &st2);
             friend bool operator>(const String & st1,const String & st2);
             friend bool operator==(const String & st,const String & st2);
             friend ostream & operator<<(ostream & os,const String & st);
             friend istream & operator>>(istream & is,String & st);
             //static function
             static int HowMany();
      };
      
#endif
      


  string1.cpp

#include <cstring>
#include "string1.h"
using std::cin;
using std::cout;

int String::num_strings = 0;
int String::HowMany()
{
    return num_strings;
    }
    
String::String(const char *s)
{
                     len = std::strlen(s);
                     str = new char[len+1];
                     std::strcpy(str,s);
                     num_strings++;
                     }
                     
String::String()
{
                len = 4;
                str = new char[1];
                str[0] = '\0';
                num_strings++;
                }
                
String::String(const String & st)
{
                     num_strings++;
                     len = st.len;
                     str = new char[len+1];
                     std::strcpy(str,st.str);
                     }
                     
String::~String()
{
                  --num_strings;
                  delete []str;
                  }
                  
//overloaded operator methods
String & String::operator=(const String & st)
{
       if(this == &st)
               return *this;
       delete []this;
       len = st.len;
       str = new char[len+1];
       std::strcpy(str,st.str);
       return *this;
       }
       
String & String::operator=(const char *s)
{
       delete []str;
       len = std::strlen(s);
       str = new char[len+1];
       std::strcpy(str,s);
       return *this;
       }
       
//read-write char access for non-const String
char & String::operator[](int i)
{
     return str[i];
     }
     
const char & String::operator[](int i)const
{
      return str[i];
      
      }

bool operator<(const String & st1,const String & st2)
{
     return (std::strcmp(st1.str,st2.str)<0);
     }
     
bool operator>(const String &st1,const String &st2)
{
     return st2.str<st1.str;
     }
     
bool operator==(const String & st1,const String &st2)
{
     return (std::strcmp(st1.str,st2.str)==0);
     }
     
//simple String output
ostream & operator<<(ostream &os,const String & st)
{
        os<<st.str;
        return os;
        }

istream & operator>>(istream & is,String & st)
{
        char temp[String::CINLIM];
        is.get(temp,String::CINLIM);
        if(is)
              st = temp;
        while(is && is.get()!='\n')
                 continue;
        return is;
        }


  saystring1.cpp

#include <iostream>
#include "string1.h"
const int ArSize = 10;
const int MaxLen = 81;

int main()
{
    using std::cout;
    using std::cin;
    using std::endl;
    String name;
    cout<<"Hi,what's your name?\n>> ";
    cin>>name;
    
    cout<<name<<", please enter up to "<<ArSize<<" short sayings <empty line to quit>:\n";
    String sayings[ArSize];
    char temp[MaxLen];
    int i;
    for(i = 0;i<ArSize;i++)
    {
          cout<<i+1<<": ";
          cin.get(temp,MaxLen);
          while(cin && cin.get()!='\n')
                    continue;
          if(!cin || temp[0] == '\0')
                  break;
          else
              sayings[i] = temp;
          }
    int total = i;
    
    cout<<"Here are your sayings:\n";
    for(i = 0;i<total;i++)
          cout<<sayings[i][0]<<": "<<sayings[i]<<endl;
    
    int shortest = 0;
    int first = 0;
    for(i=1;i<total;i++)
    {
                        if(sayings[i].length()<sayings[shortest].length())
                                                                          shortest = i;
                        if(sayings[i]<sayings[first])
                                                    first = i;
                        }
                        
    cout<<"Shorest saying:\n"<<sayings[shortest]<<endl;
    cout<<"Frist aplhabetically:\n"<<sayings[first]<<endl;
    cout<<"This program used "<<String::HowMany()<<" String objects.Bye.\n";
    
    system("pause");
    return 0;
    }


构造函数中使用new
  如果在构造函数中使用new来初始化指针 成员 ,则应在析构中使用delete
  new和delete必须相互兼容。new对应对delete,new[]对应 于delete[]
  如果有多个构造函数,则必须以相同的方式使用new,要么都带中括号,要么都不带。因为析构函数仅有一个,必须所有的构造函数都可兼容
指针和对象
  使用常规表示方法来声明指向对象的指针
    String * q;
  可以将指针初始化为指向已有的对象
    String * q = & sayings[0];
  可以使用new来初始化指针,将创建一个新的对象
    String * f = new String(sayings[choice]);
  对类使用new将调用 相应的类构造函数来初始化新创建的对象
  可以使用->操作符通过指针访问类方法
  可以对对象指针应用解除引用操作符(*)来获取对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值