当前位置: 首页 > news >正文

C++练习3

 

 练习

终端上输出 3.14 要求实现 myDouble的 operator+ operator- operator*

class myOut

{

没有私有成员 只有公开函数

}

myOut out;

out << 1 终端输出1

out << 3.14 终端输出3.14

out << "hello" 终端输出hello

out << endl 终端输出换行符

不允许使用 cout 去做,用printf 去做

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <vector>
#include <memory>

using namespace std;

class myDouble{
    private:
        int a;
        int b;

    public:
        myDouble(int a=0,int b=0):a(a),b(b){}
        void show(){
            cout << a << "." << abs(b) << endl;
        }
        myDouble operator+(const myDouble& r){
            myDouble res;
            res.a = this->a + r.a;
            res.b = this->b + r.b;
            return res;
        }
        myDouble  operator-(const myDouble& r){
            myDouble res;
            res.a = this->a - r.a;
            res.b = this->b - r.b;
            return res;
        }
    myDouble  operator*(const myDouble& r){
            myDouble res;
            res.a = this->a * r.a;
            res.b = this->b * r.b;
            return res;
        }
};
class myOut {
    public:
        // 处理整数
        myOut& operator<<(int value) {
            printf("%d", value);
            return *this;
        }

        // 处理浮点数(自动调整格式)
        myOut& operator<<(double value) {
            printf("%g", value);
            return *this;
        }

        // 处理字符串
        myOut& operator<<(const char* str) {
            printf("%s", str);
            return *this;
        }

        // 处理endl(函数指针)
        myOut& operator<<(myOut& (*manip)(myOut&)) {
            return manip(*this);
        }
};

// 实现全局的endl函数
myOut& endl(myOut& out) {
    printf("\n");
    return out;
}
int main(int argc,const char** argv){
    myDouble x(3,14);
    myDouble y(2,4);
    myDouble temp = x + y;
    temp.show();
    temp = x - y;
    temp.show();
    temp = x * y;
    temp.show();
    myOut out;
    out << 1;
    out << 3.14;    // 输出: 3.14
    out << "hello"; // 输出: hello
    out << endl;    // 输出换行

    // 链式调用
    out << 1 << 3.1415926 << " world" << endl; // 输出: 13.1416 world

}

 

刷题

相关文章:

  • Seg-Zero:通过认知强化实现的推理链引导分割
  • 【NLP 51、一些LLM模型结构上的变化】
  • 【 <二> 丹方改良:Spring 时代的 JavaWeb】之 Spring Boot 中的国际化:支持多语言的 RESTful API
  • 短视频文案--钓鱼女和滑板女
  • Review --- 线程基础
  • 【实战】LLaMA-Factory 如何做 LLM 的多轮对话微调
  • 【C++笔记】C++常见二叉树OJ和拓扑排序
  • 31天Python入门——第19天:再学面向对象·一切皆对象
  • Css:如何解决绝对定位子元素内容被父级元素overflow:hidden属性剪裁
  • 可实现黑屏与蓝屏反应的屏幕隐私保护软件分享
  • 《高校辅导员》考试考哪些内容?
  • nacos-sdk-go v2.29 中一个拼写错误,我定位了3个小时 ……
  • 主流车辆监控管理系统对比分析
  • 极客说|重大发布:vLLM V1
  • 2011-2019年各省地方财政国债还本付息支出数据
  • 【Tauri2】011——菜单menu(2)
  • 什么是 Java 泛型
  • 0-1背包问题和最长公共子序列
  • Java打卡-Day23-文件、IO流
  • 探索 Kubernetes 网络穿透:如何从外部访问 K8s Pod 地址
  • 深圳营销网站建设公司/提高网站搜索排名
  • 网站运营如何做/站长工具之家
  • 江苏网站建设教程/网页链接
  • 网站的大量图片存储格式/软文范文大全
  • 企业免费邮箱/seo百科
  • 哪家网站建设做的好/做国外网站