运算符重载 定义为类成员函数or非成员函数

本文介绍了C++中运算符重载的基本概念,并通过一个具体的销售数据类实例展示了何时应将运算符重载作为成员函数或非成员函数。此外,还提供了输入和输出运算符的实现示例。

运算符重载 定义为类成员函数or非成员函数

定义为类成员函数

1. 赋值(=)、下标([ ])、 函数调用(( ))和成员访问箭头(->)
2. 重载的运算符会改变对象状态(如:复合赋值运算符(+=、 -=、 = 、 /= 、 %= 等)递增、递减运算符正(+)、负(-)运算符)与类对象密切相关如: 解引用(

定义为非成员函数

具有 对称性 的运算符, 运算符对象可以转移到任意一端(如算术运算符 (+、 - 、 * 、 / 、 %等),相等性运算符 (==、 !=),关系运算符(>、 >= 、 <、 <=),位运算符
输入(>>)、输出运算符(<<)必须是非成员函数。

参考代码

参考 https://github.com/pezy/CppPrimer/blob/master/ch14/ex14_02_sales_data.h

// sales_data.h
    #include <string>
    #include <iostream>
    #include <fstream>
    class sales_data
    {
        friend std::istream& operator>>(std::istream &is, sales_data &data);
        friend std::ostream& operator<<(std::ostream &os, const sales_data &data);
        friend sales_data operator+(const sales_data &lhs, const sales_data &rhs);

    public:
        sales_data(const std::string &No, double price,unsigned sold) 
            : bookNo(No), revenue(price * sold), units_sold(sold)
        {
        }
        sales_data() :sales_data("", 0.0f, 0)
        {
        }
        sales_data(const std::string &No) :sales_data(No, 0.0f, 0)
        {
        }
        sales_data(std::ifstream &fin);
        std::string isbn() const    {   return bookNo;  }
        sales_data& operator+=(const sales_data &rhs);

    private:
        std::string bookNo;
        double revenue;
        unsigned units_sold;
        inline double avr_price();
    };
        inline double sales_data::avr_price()
    {
        return revenue / units_sold;
    }

    std::istream& operator>>(std::istream &is, sales_data &data)
    {
        double price = 0.0;
        is >> data.bookNo >> price >> data.units_sold;
        if (is)
            data.revenue = price * data.units_sold;
        else
            data = sales_data();
        return is;
    }

    std::ostream& operator<<(std::ostream &os, const sales_data &data)
    {
        os << data.bookNo << "  " << data.revenue << "  " 
            << data.units_sold;
        return os;
    }

    sales_data operator+(const sales_data &lhs, const sales_data &rhs)
    {
        sales_data ret = lhs;
        ret += rhs;
        return ret;
    }
    sales_data& sales_data::operator += (const sales_data &rhs)
    {
        if (bookNo == rhs.bookNo)
        {
            revenue += rhs.revenue;
            units_sold += rhs.units_sold;
            return *this;

        }
        else
            //throw(std::string("two adders' bookNo should be the same"));
            throw("two adders' bookNo should be the same");
        //assert(bookNo == rhs.bookNo);
        //std::cout << "two adders' bookNo should be the same" << std::endl;
    }

    sales_data::sales_data(std::ifstream &fin)
    {
        fin >> *this;
    }
// main.cpp
    #include <iostream>
    #include "sales_data.h"
    #include <string>
    int main()
    {

        sales_data data1("c++ primier2", 25, 20);
        sales_data data2("c++ primier1", 20, 10);
        try
        {
            std::cout << data1 + data2 << std::endl;
        }
        catch (const char* str)
        {
            std::cout << str << std::endl;
        }
        return 0;
    }
### 如何在多项式类中实现运算符重载 #### C++ 中的多项式类运算符重载 在 C++ 中,可以通过定义一个 `Polynomial` 类来表示多项式,并利用运算符重载技术实现多项式的加法、减法和乘法等功能。以下是具体实现方式: 1. **类设计** 定义一个 `Polynomial` 类,其中包含存储系数的数据结构(通常是一个动态数组或 `std::vector<int>`),以及必要的函数。 2. **运算符重载** 使用友元函数函数的方式重载运算符。例如,可以重载 `+` 来实现两个多项式的相加。 ```cpp #include <iostream> #include <vector> class Polynomial { private: std::vector<double> coefficients; public: // 构造函数 Polynomial(const std::vector<double>& coeffs) : coefficients(coeffs) {} // 获取最高次幂 int degree() const { return static_cast<int>(coefficients.size()) - 1; } // 加法运算符重载 Polynomial operator+(const Polynomial& other) const { int maxDegree = std::max(degree(), other.degree()); std::vector<double> result(maxDegree + 1, 0); for (int i = 0; i <= maxDegree; ++i) { double coefSelf = (i <= degree()) ? coefficients[i] : 0; double coefOther = (i <= other.degree()) ? other.coefficients[i] : 0; result[i] = coefSelf + coefOther; } return Polynomial(result); } // 打印多项式 void print() const { for (int i = degree(); i >= 0; --i) { if (coefficients[i] != 0) { if (i != degree()) std::cout << " + "; std::cout << coefficients[i]; if (i > 0) std::cout << "x"; if (i > 1) std::cout << "^" << i; } } std::cout << std::endl; } }; // 测试代码 int main() { Polynomial p1({2, 0, 3}); // 表示 2 + 3x^2 Polynomial p2({1, 4}); // 表示 1 + 4x Polynomial sum = p1 + p2; sum.print(); return 0; } ``` 上述代码展示了如何通过重载 `operator+` 函数实现两个多项式的加法[^1]。 --- #### Python 中的多项式类运算符重载 Python 提供了更灵活的方式来实现运算符重载。同样可以通过定义一个 `Polynomial` 类并重载相应的特殊方法(如 `__add__`, `__sub__`, 和 `__mul__`)来实现多项式的各种运算。 ```python from collections import defaultdict class Polynomial: def __init__(self, coefficients=None): self.coeffs = defaultdict(float) if coefficients is not None: for exp, coeff in enumerate(coefficients): self.coeffs[exp] = float(coeff) @property def degree(self): if not self.coeffs: return 0 return max(self.coeffs.keys()) def __add__(self, other): result = Polynomial() all_exponents = set(self.coeffs.keys()).union(other.coeffs.keys()) for exponent in all_exponents: result.coeffs[exponent] = self.coeffs.get(exponent, 0) + other.coeffs.get(exponent, 0) return result def __str__(self): terms = [] for exp in sorted(self.coeffs.keys(), reverse=True): if self.coeffs[exp] != 0: term = f"{self.coeffs[exp]}x^{exp}" if exp > 1 else str(self.coeffs[exp]) if exp == 0 else f"{self.coeffs[exp]}x" terms.append(term) return " + ".join(terms) or "0" # 测试代码 p1 = Polynomial([2, 0, 3]) # 表示 2 + 3x^2 p2 = Polynomial([1, 4]) # 表示 1 + 4x sum_p = p1 + p2 print(sum_p) # 输出:3.0x^2 + 4.0x + 3.0 ``` 此代码片段实现了多项式的加法操作,并通过字符串化方法展示结果[^1]。 --- #### 总结 无论是 C++ 还是 Python,在实现多项式类时都可以借助面向对象的思想将多项式的属性(如系数列表)和行为(如加法、减法等)封装起来。C++ 更注重性能优化,适合工程场景;而 Python 则提供了更高的灵活性和易读性,便于快速原型开发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值