cc21a -c++重载成员操作符*,->,代码示范

cc21a重载成员操作符*,->,

*,解引用操作符

->箭头操作符,用于智能指针类

 1 #include "pointer.h" //pointer.cpp
 2 #include "string.h"
 3 
 4 Pointer::Pointer() :ptr(0) {}
 5 
 6 Pointer::Pointer(String const &n)
 7 {
 8     ptr = new String(n); //ptr指针指向String
 9 }
10 Pointer::~Pointer()
11 {
12     delete ptr;
13 }
14 String Pointer::errorMessage("未初始化的指针");
15 String &Pointer::operator*() //*是解引用操作,得到的是指针所指向的对象
16 {
17     if (!ptr)
18         throw errorMessage;
19     return *ptr;
20 }
21 String *Pointer::operator->() const//指针成员操作符
22 {
23     if (!ptr)
24         throw errorMessage;
25     return ptr;
26 }

 

#define _CRT_SECURE_NO_WARNINGS //string.cpp
#include<iostream>
#include<cstring>
#include "string.h"

String::String(char const *chars)//接收普通字符串
{
    chars = chars ? chars : "";
    ptrChars = new char[std::strlen(chars) + 1];
    std::strcpy(ptrChars,chars);
}
String::String(String const &str) //接收String类的对象
{
    ptrChars = new char[std::strlen(str.ptrChars) + 1];
    std::strcpy(ptrChars,str.ptrChars);
}
String::~String()
{
    delete[] ptrChars;
}
void String::display() const
{
    std::cout << ptrChars << std::endl;
}
#pragma once
#ifndef POINTER_H  //头文件保护,防止多重包含 //pointer.h
#define POINTER_H

//pointer类里面用到了String,所以需要前置声明
class String;
//智能指针:对指针使用进行计数 

class Pointer
{
public:
    Pointer();
    Pointer(String const &n);
    ~Pointer();

    String &operator*();
    String *operator->() const; //智能指针

private:
    String *ptr;
    static String errorMessage;//静态字符串给出错误信息

};
#endif // !POINTER_H
#pragma once
#ifndef STRING_H  //string.h
#define STRING_H

class String
{
public:
    String(char const *chars = "");//*chars,不要少写了s, 没有s,char就是关键字了,就会报错
    String(String const &str);
    ~String();
    void display() const;
private:
    char *ptrChars;

};

#endif
#define _CRT_SECURE_NO_WARNINGS

#include<iostream>    //功能:重载成员操作符。txwtech- //cc21a_demo.cpp
#include "string.h"
#include "pointer.h"
using namespace std;

int main()   //cc21a_demo.cpp
{
    String s("hello String");
    s.display();
    //cout << "hello" << endl;

    String *ps = &s;
    ps->display(); 

    try
    {
        Pointer p1("c++");
        p1->display();

        Pointer p2;
        p2->display();
    }
    catch(String const &error)
    {
        error.display();
        
    }
    system("pause");
    return 0;
}
posted @ 2019-12-26 16:20  txwtech  阅读(347)  评论(0编辑  收藏  举报