C++:更改单个输出操作的格式输出

标签 c++ c++11

我有一个 C++ 类(class)的练习,但我不理解所提供的代码。问题是:如果我们可以更改格式以仅输出单个值(如以下代码片段所示),那就太好了

Form gen4(4);

void f(double d){
  Form sci8=gen4;
  sci.scientific().setprecision(8);
  std::cout << gen4(d) << " back to old options: "
  << d << std::endl;
}

gen4 应该成为某种“某种”运算符,将输出参数仅应用于单个输出操作。

我了解要求的内容,并且了解如何定义自定义 I/O 操纵器:

Form gen4(4);

void f2(double d){
  Form sci8=gen4;
  sci8.scientific().setprecision(8);
  std::cout << sci8 << d << endl;
  // from now on, all output will use the format defined by sci8
  // (until changed again)
}

所以我有 2 个问题。

  1. 截取的第一个代码有何意义?他用参数 d 第二次调用 gen4 的构造函数,但是如何以及为什么应该第二次调用构造函数,即使对象已经存在?
  2. 我如何实际制作这样一个仅适用于下一个操作的自定义 I/O 操纵器?这对我来说似乎很棘手,我不知道/不知道我应该做什么。

最佳答案

为了完整性,这里是我使用评论中给出的建议的答案: 表单.h

#pragma once
#include <iostream>

class Form{
public:
  int prc, wdt, fmt;
  bool sci = false;
  Form(int p=6) : prc(p) {
    fmt=wdt=0;
  }
  Form& scientific() {
    sci = true;
    return *this;
  }
  Form& precision(int p) {
    prc=p;
    return *this;
  }
  Form& operator()(double d){
    std::ios::fmtflags f(std::cout.flags());
    if(sci){
      std::cout.setf(std::ios_base::scientific);
      std::cout.precision(prc);
    }
    std::cout << d;
    std::cout.flags(f);
    return *this;
  }
};

std::ostream& operator<<(std::ostream& os, const Form& f){
  return os;
}

主要.cpp

#include <iostream>

#include "include/form.h"

Form gen4(4);

void f(double d){
  Form sci8=gen4;
  sci8.scientific().precision(8);
  std::cout << sci8(d) << " back to old options: " << d << std::endl;
}

int main() {
  // Task1
  f(64959.454243425);
  return 0;
}

给出预期的结果:

6.49594542e+04 back to old options: 64959.454

感谢 Igor Tandetnik

关于C++:更改单个输出操作的格式输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41537040/

相关文章:

c++ - Cmake找不到boost库

C++ 模板参数作为函数调用名称

c++ - 判断模板参数包中 "optimal"公共(public)数值类型

c++ - 从基类c++的 vector 中的派生类调用虚方法

c++ - 左右移动负整数是否定义了行为?

c++ - clang 和 gcc 中的这个警告似乎不正确

c++ - 什么是 "Unary Constructor"?

采用 float 或 double 的 C++ 模板函数

c++ - 如何使用 C++ 列出 unix 用户的所有补充组

C++ - 哪些是可变的 "Uint "?