为ostream设置值

Putting a value to ostream

本文关键字:设置 ostream      更新时间:2023-10-16

下面的代码解析for语句,但我不确定在调用方法write(...)时如何将任何值放入ostream中。我能做什么?(例如write("for (........."))

#include <ostream>
#include <iostream>
using namespace std;
//I cut out the declaration bit here
typedef const string type;
private:
type *initializer;
type *condition;
type *increment;
type *body;
public:
void write(ostream& stream) const {
      stream
        << "for ("
        << *initializer << "; "
        << *condition << "; "
        << *increment << ")n{n"
        << *body
        << "}";
}

我想您试图学习使用ostream作为函数中的输入。但你似乎把如何使用classmethod混合在一起。也许这没有用,但我可以给你一个小片段,给你一些意见。

#include <iostream>
#include <string>
using namespace std;
typedef const string type;
type *init;
type *cond;
type *incr;
type *body;

void write(ostream& stream) {
      stream
        << "for ("
        << *init << "; "
        << *cond << "; "
        << *incr << ")n{n"
        << *body
        << "n}";
}

int main(int argc, char* argv[])
{
    const string ini = "int i = 0";
    const string con = "i < 10";
    const string inc = "i++";
    const string bod = "cout << i << endl;";
    init = &ini;
    cond = &con;
    incr = &inc;
    body = &bod;
    write(cout);
    return 0;
}

请尝试此代码,检查并阅读更多详细信息。