C++两个类使用同一个友元函数来进行相互调用

本文通过一个C++代码示例介绍了如何让两个类使用同一个友元函数进行相互调用。代码展示了一个基类A,派生类B和类C,它们之间的关系以及友元函数callCFunc的实现。通过main函数运行结果,展示了友元函数如何访问类的私有成员并显示各自的内容。
摘要由CSDN通过智能技术生成

http://topic.csdn.net/u/20110519/23/cce5ff99-c13b-4d3b-9e47-d0fab4ba8da9.html?seed=731244564&r=73412830#r_73412830

问题的引入是论坛上面的一个惊动“特技大牛”的讨论,呵呵,欢迎拍砖~~

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是一个使用函数重载和友元函数实现分数运算的C++程序: ```cpp #include <iostream> using namespace std; class Fraction { public: Fraction(int n = 0, int d = 1) : num(n), den(d) {} friend ostream& operator<<(ostream& out, const Fraction& f); friend istream& operator>>(istream& in, Fraction& f); friend Fraction operator+(const Fraction& f1, const Fraction& f2); friend Fraction operator-(const Fraction& f1, const Fraction& f2); friend Fraction operator*(const Fraction& f1, const Fraction& f2); friend Fraction operator/(const Fraction& f1, const Fraction& f2); private: int num, den; }; ostream& operator<<(ostream& out, const Fraction& f) { out << f.num << "/" << f.den; return out; } istream& operator>>(istream& in, Fraction& f) { char c; in >> f.num >> c >> f.den; return in; } int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } Fraction operator+(const Fraction& f1, const Fraction& f2) { int n = f1.num * f2.den + f2.num * f1.den; int d = f1.den * f2.den; int g = gcd(n, d); return Fraction(n / g, d / g); } Fraction operator-(const Fraction& f1, const Fraction& f2) { int n = f1.num * f2.den - f2.num * f1.den; int d = f1.den * f2.den; int g = gcd(n, d); return Fraction(n / g, d / g); } Fraction operator*(const Fraction& f1, const Fraction& f2) { int n = f1.num * f2.num; int d = f1.den * f2.den; int g = gcd(n, d); return Fraction(n / g, d / g); } Fraction operator/(const Fraction& f1, const Fraction& f2) { int n = f1.num * f2.den; int d = f1.den * f2.num; int g = gcd(n, d); return Fraction(n / g, d / g); } int main() { Fraction f1, f2; char op; cout << "Enter first fraction: "; cin >> f1; cout << "Enter operator (+, -, *, /): "; cin >> op; cout << "Enter second fraction: "; cin >> f2; switch (op) { case '+': cout << f1 << " + " << f2 << " = " << f1 + f2 << endl; break; case '-': cout << f1 << " - " << f2 << " = " << f1 - f2 << endl; break; case '*': cout << f1 << " * " << f2 << " = " << f1 * f2 << endl; break; case '/': cout << f1 << " / " << f2 << " = " << f1 / f2 << endl; break; default: cout << "Invalid operator" << endl; } return 0; } ``` 在这个程序中,我们定义了一个Fraction来表示分数,其中num表示分子,den表示分母。我们重载了输出运算符<<和输入运算符>>,以便能够直接使用cout和cin输出和输入分数。我们还定义了四个友元函数,分别是加法运算符+、减法运算符-、乘法运算符*和除法运算符/,用于进行分数的加减乘除运算。在每个运算符函数中,我们先计算出运算结果的分子和分母,然后使用辗转相除法求出最大公约数,最后将分子和分母同时除以最大公约数,得到最简分数形式的结果。在main函数中,我们首先使用cin输入两个分数和一个运算符,然后根据运算符调用相应的运算符函数进行运算,并使用cout输出结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值