main.cpp
/*
Date: 12/03/21 16:01
Description: 重载成员访问操作符
成员访问操作符
解引用操作符:*
箭头操作符:->
复习
管理指针成员
定义智能指针类
class Pointer ----> class String
*/
#include<iostream>
#include "string.h"
#include "pointer.h"
using namespace std;
int main()
{
String s("Hello String");
s.display();
String *ps = &s;
ps->display();
try{
Pointer p1("C++");
p1->display();
String s = *p1;
s.display();
Pointer p2;
p2->display();
}catch(String const &error)
{
error.display();
}
return 0;
}
string.h
#ifndef STRING_H
#define STRING_H
class String
{
public:
String(char const *chars = "");
String(String const &str);
~String();
void display()const;
private:
char *ptrChars;
};
#endif
string.cpp
#include<iostream>
#include<cstring>
#include "string.h"
String::String(char const *chars)
{
chars = chars ? chars : "";
ptrChars = new char[strlen(chars)+1];
strcpy(ptrChars,chars);
}
String::String(String const &str)
{
ptrChars = new char[strlen(str.ptrChars)+1];
strcpy(ptrChars,str.ptrChars);
}
String::~String()
{
delete[] ptrChars;
}
void String::display()const
{
std::cout<<ptrChars<<std::endl;
}
pointer.h
#ifndef POINTER_H
#define POINTER_H
class String;
//智能指针:对指针使用进行计数
class Pointer
{
public:
Pointer();
Pointer(String const &n);
~Pointer();
String &operator*();
String *operator->()const;
private:
String *ptr;
static String errorMessage;
};
#endif
pointer.cpp
#include "pointer.h"
#include "string.h"
Pointer::Pointer():ptr(0){}
Pointer::Pointer(String const &n)
{
ptr = new String(n);
}
Pointer::~Pointer()
{
delete ptr;
}
String Pointer::errorMessage("Uninitialized pointer");
String &Pointer::operator*()
{
return *ptr;
}
String *Pointer::operator->()const
{
if(!ptr)
throw errorMessage;
return ptr;
}