[参照解除](Unreference)オペレータと矢印オペレータ

2196 ワード

#include <iostream>
#include "string.h"
#include "pointer.h"

using namespace std;

int main ()
{
	String s("xiaocui");
	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();
	}
	
	system("pause");
	return 0;
}
#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
#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
#include <iostream>
#include <ostream>
#include "string.h"

String::String(char const *chars)
{
	chars = chars ? chars : "";  //                   ,
	ptrChars = new char[std::strlen(chars) + 1]; //  1           \0,
	std::strcpy(ptrChars,chars);
}

String::String(String const &str)
{
	ptrChars = new char[std::strlen(str.ptrChars) + 1];
	std::strcpy(ptrChars,str.ptrChars);
}

String::~String()   //               new      ,      
{
	delete[] ptrChars;
}

void String::display() const
{
	std::cout << ptrChars << std::endl;
}
#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*()  //           ,
{
	if(!ptr)
		throw errorMessage;
	return *ptr;
}

String *Pointer::operator->() const
{
	if(!ptr)
		throw errorMessage;
	return ptr;
}