在不更改main()函数的情况下更改C ++输出 [英] Changing C++ output without changing the main() function

查看:248
本文介绍了在不更改main()函数的情况下更改C ++输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream.h>
void main()
{
    cout<<"Love";
}

问题是我们如何将这个程序的输出变成

The question is how can we change the output of this program into "I Love You" without making any change in main().

推荐答案

好的,修复你的主要功能和iostream.h ...这是方式

Ok, fixing your main function and iostream.h ... This is the way

#include <iostream>

// to make sure std::cout is constructed when we use it
// before main was called - thxx to @chappar
std::ios_base::Init stream_initializer;

struct caller {
    caller() { std::cout << "I "; }
    ~caller() { std::cout << " You"; }
} c;

// ohh well, for the br0ken main function
using std::cout;

int main()
{
    cout<<"Love";
}

我想我应该解释为什么。代码定义了一个具有构造函数和析构函数的结构体。构造函数在创建结构体的对象时运行,析构函数在对象被销毁时运行。现在,在结构体定义的末尾,你可以放置类型为 caller 的声明器。

I figured i should explain why that works. The code defines a structure that has a constructor and a destructor. The constructor is run when you create an object of the struct and the destructor is run when that object is destroyed. Now, at the end of a struct definition, you can put declarators that will have the type caller.

因此,我们上面所做的是创建一个名为 c 的对象,程序启动 - 即使在main运行之前。当程序终止时,对象被销毁,析构函数被运行。之间,印刷爱。

So, what we did above is creating an object called c which is constructed (and the constructor called) at program start - even before main is run. And when the program terminates, the object is destroyed and the destructor is run. In between, main printed "Love".

这种模式实际上是由 RAII 这个术语非常熟知的,它通常在构造函数中声明一些资源并释放它再次在析构函数中调用。

That pattern actually is very well known by the term RAII which usually claims some resource in the constructor and releases it again in the destructor call.

这篇关于在不更改main()函数的情况下更改C ++输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆