admin 管理员组文章数量: 887031
C++
定义:
Salesitem.h
/*
* This file contains code from "C++ Primer, Fifth Edition", by Stanley B.
* Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the
* copyright and warranty notices given in that book:
*
* "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo."
*
*
* "The authors and publisher have taken care in the preparation of this book,
* but make no expressed or implied warranty of any kind and assume no
* responsibility for errors or omissions. No liability is assumed for
* incidental or consequential damages in connection with or arising out of the
* use of the information or programs contained herein."
*
* Permission is granted for this code to be used for educational purposes in
* association with the book, given proper citation if and when posted or
* reproduced.Any commercial use of this code requires the explicit written
* permission of the publisher, Addison-Wesley Professional, a division of
* Pearson Education, Inc. Send your request for permission, stating clearly
* what code you would like to use, and in what specific way, to the following
* address:
*
* Pearson Education, Inc.
* Rights and Permissions Department
* One Lake Street
* Upper Saddle River, NJ 07458
* Fax: (201) 236-3290
*//* This file defines the Sales_item class used in chapter 1.
* The code used in this file will be explained in
* Chapter 7 (Classes) and Chapter 14 (Overloaded Operators)
* Readers shouldn't try to understand the code in this file
* until they have read those chapters.
*/#ifndef SALESITEM_H
// we're here only if SALESITEM_H has not yet been defined
#define SALESITEM_H// Definition of Sales_item class and related functions goes here
#include <iostream>
#include <string>class Sales_item {// these declarations are explained section 7.2.1, p. 270 // and in chapter 14, pages 557, 558, 561friend std::istream& operator>>(std::istream&, Sales_item&);friend std::ostream& operator<<(std::ostream&, const Sales_item&);friend bool operator<(const Sales_item&, const Sales_item&);friend booloperator==(const Sales_item&, const Sales_item&);
public:// constructors are explained in section 7.1.4, pages 262 - 265// default constructor needed to initialize members of built-in type
#if defined(IN_CLASS_INITS) && defined(DEFAULT_FCNS)Sales_item() = default;
#elseSales_item() : units_sold(0), revenue(0.0) { }
#endifSales_item(const std::string& book) :bookNo(book), units_sold(0), revenue(0.0) { }Sales_item(std::istream& is) { is >> *this; }
public:// operations on Sales_item objects// member binary operator: left-hand operand bound to implicit this pointerSales_item& operator+=(const Sales_item&);// operations on Sales_item objectsstd::string isbn() const { return bookNo; }double avg_price() const;// private members as before
private:std::string bookNo; // implicitly initialized to the empty string
#ifdef IN_CLASS_INITSunsigned units_sold = 0; // explicitly initializeddouble revenue = 0.0;
#elseunsigned units_sold;double revenue;
#endif
};// used in chapter 10
inline
bool compareIsbn(const Sales_item& lhs, const Sales_item& rhs)
{return lhs.isbn() == rhs.isbn();
}// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&);inline bool
operator==(const Sales_item& lhs, const Sales_item& rhs)
{// must be made a friend of Sales_itemreturn lhs.units_sold == rhs.units_sold &&lhs.revenue == rhs.revenue &&lhs.isbn() == rhs.isbn();
}inline bool
operator!=(const Sales_item& lhs, const Sales_item& rhs)
{return !(lhs == rhs); // != defined in terms of operator==
}// assumes that both objects refer to the same ISBN
Sales_item& Sales_item::operator+=(const Sales_item& rhs)
{units_sold += rhs.units_sold;revenue += rhs.revenue;return *this;
}// assumes that both objects refer to the same ISBN
Sales_item
operator+(const Sales_item& lhs, const Sales_item& rhs)
{Sales_item ret(lhs); // copy (|lhs|) into a local object that we'll returnret += rhs; // add in the contents of (|rhs|) return ret; // return (|ret|) by value
}std::istream&
operator>>(std::istream& in, Sales_item& s)
{double price;in >> s.bookNo >> s.units_sold >> price;// check that the inputs succeededif (in)s.revenue = s.units_sold * price;elses = Sales_item(); // input failed: reset object to default statereturn in;
}std::ostream&
operator<<(std::ostream& out, const Sales_item& s)
{out << s.isbn() << " " << s.units_sold << " "<< s.revenue << " " << s.avg_price();return out;
}double Sales_item::avg_price() const
{if (units_sold)return revenue / units_sold;elsereturn 0;
}
#endif
主函数:
#include <iostream>
#include "Salesitem.h"using namespace std; class Person
{
public:/*不允许重载内置类型,必须有一个类类型,重载的操作符不会改变优先级,一般不要重载逻辑运算符,& ,运算符,operator本质是一个函数,可以使用友元friend来声明非成员函数的操作符重载,一般把赋值操作定义为成员函数*/void operator+(const Person& rhs){cout << "执行了重载的加法操作" << endl;}
};int main()
{Person p1, p2;p1 + p2;Sales_item item1, item2;cin >> item1 >> item2;cout << item1 + item2 << endl;//另外一种写法,调用operator+函数:cout << operator+(item1, item2) << endl;return 0;
}
结果:
赋值操作符重载:
#include <iostream>using namespace std; class String
{
public:String(char const* chars = "");String& operator=(String const&);//类似的String& operator=(char const*);String& operator=(char);void print();
private:char* ptrChars;
};
String& String::operator=(String const& str)//赋值操作符重载
{if (strlen(ptrChars) != strlen(str.ptrChars)){char* ptrHold = new char[strlen(str.ptrChars)+1]; //动态创建一个字符串delete[] ptrChars;//删除原来的字符串ptrChars = ptrHold;//变更ptrChar所指的字符串大小}std::strcpy(ptrChars, str.ptrChars);//复制参数到成员变量中return *this; //返回当前对象
}
String::String(char const* chars)
{chars = chars ? chars : ""; //判断字符串是否为空,将空字符串分配为空串ptrChars = new char[std::strlen(chars) + 1];//动态分配字符串大小std::strcpy(ptrChars, chars);//复制字符串到成员指针变量
}
void String::print()
{cout << ptrChars << endl;
}
int main()
{String s("hello");String s2("Dog");s.print();s2.print();s = s2;s.print();return 0;
}
下标操作符重载:
#include <iostream>using namespace std; class String
{
public:String(char const* chars = "");char& operator[](std::size_t index) throw(String);char operator[](std::size_t index) const throw(String);void print();
private:char* ptrChars;static String erroMessage;
};
String String::erroMessage("Subscript out of range");
char& String::operator[](std::size_t index) throw(String)//下标操作符重载
{if (index >= std::strlen(ptrChars))throw erroMessage;return ptrChars[index];
}
char String::operator[](std::size_t index) const throw(String) //不可变的字符串,常量
{if (index >= std::strlen(ptrChars))throw erroMessage;return ptrChars[index];
}
String::String(char const* chars)
{chars = chars ? chars : ""; //判断字符串是否为空,将空字符串分配为空串ptrChars = new char[std::strlen(chars) + 1];//动态分配字符串大小std::strcpy(ptrChars, chars);//复制字符串到成员指针变量
}
void String::print()
{cout << ptrChars << endl;
}
int main()
{String s("hello");s.print();cout << s[0] << endl;s[0] = 'A';s.print();String const s2("dog"); //将会调用const操作符重载cout << s2[2] << endl;return 0;
}
成员访问操作符重载:
智能指针类的解引用操作符*和箭头->操作符的重载
主函数main.c
#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(); //->操作符重载,p1->相当于一个指向String类的指针,即Pointer里的ptrString s = *p1; //*p1相当于一个指向String类的指针,即Pointer里的ptrs.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[std::strlen(chars) + 1];std::strcpy(ptrChars, chars);
}
String::String(String const& str)
{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;
}
pointer.h
#ifndef POINTER_H
#define POINTER_H
#include "String.h"
class Pointer
{
public:Pointer();Pointer(String const& n); ~Pointer();String& operator*();String* operator->() const;
private:String* ptr; //ptr为String类的指针static String errorMessage;
};
#endif
pointer.cpp
#include "pointer.h"
#include "String.h"
Pointer::Pointer():ptr(0){}
Pointer::Pointer(String const& n)//将字符串n转化为String类
{ptr = new String(n); //将ptr指向传入的String类
}
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;
}
自增自减操作符重载
String& operator(); //前加加,返回引用
String const operator++(int);//后加加,有参数,返回拷贝String& String::operator++() //前加加
{for(std::size_t i=0;i<std::strlen(ptrChars);++i) //对字符串中的每一位进行加一操作{++ptrChars[i];}return *this;
}String const String::operator++(int)
{String copy(*this); //先复制返回当前对象的copy++(*this); //然后对当前对象加加return copy;
}
类型转换操作符重载
#include <iostream>using namespace std;//转换操作符
class Dog{
public:Dog(string n,int a,double w):name(n),age(a),weight(w){}operator int() const //转换操作符函数,不改变操作的对象,不能指定返回类型,不能有形参{return age; //显式返回int型的数据}
private:int age;double weight;string name;
};
int main()
{int a,b;a=10;b=a;cout<<b<<endl;Dog d("Bill",6,15.0);b=d;cout<<b<<endl;}
本文标签: c
版权声明:本文标题:C++ 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1686585980h13661.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论