#include<iostream.h>
void main()
{
cout<<"Love";
}
Run Code Online (Sandbox Code Playgroud)
问题是如何在不做任何改变的情况下将该程序的输出更改为"我爱你" main().
Joh*_*itb 90
好的,修复你的主要功能和iostream.h ......就是这样
#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";
}
Run Code Online (Sandbox Code Playgroud)
我想我应该解释为什么会有效.该代码定义了一个具有构造函数和析构函数的结构.在创建struct的对象时运行构造函数,并在销毁该对象时运行析构函数.现在,在结构定义的末尾,您可以放置具有该类型的声明符caller.
所以,我们上面所做的是创建一个被调用的对象c,它在程序启动时被构造(并且构造函数被调用) - 甚至在main运行之前.当程序终止时,对象将被销毁并运行析构函数.在其间,main印有"爱".
这个模式实际上是众所周知的RAII,通常在构造函数中声明一些资源并在析构函数调用中再次释放它.
War*_*ior 38
#include <iostream>
class tclass
{
public:
void operator <<(char *s)
{
std::cout<<"I"<<s<<"You"<<std::endl;
}
};
tclass cout;
int main()
{
cout<<"love";
}
Run Code Online (Sandbox Code Playgroud)
rlb*_*ond 13
不像litb那样优雅,但它有效
#include <iostream>
#include <cstdio>
#include <sstream>
#define cout printf("I love you\n"); std::ostringstream os; os
int main()
{
cout << "love";
}
Run Code Online (Sandbox Code Playgroud)
当然,你不需要使用a stringstream,你可以使用任何类operator<<.
不像litb那样优雅,但另类:
#include <iostream>
using namespace std;
int foo()
{
cout << "I Love You" << endl;
return cout.rdbuf(0);
}
int i = foo();
int main()
{
cout << "Love" << endl;
}
Run Code Online (Sandbox Code Playgroud)
像这样:
#include <iostream>
int main() {
std::cout << "I Love You" << std::endl;
return 0;
}
/*
#include<iostream.h>
void main()
{
cout<<"Love";
}
*/
Run Code Online (Sandbox Code Playgroud)
这样一来,你没有改变任何东西的 main.:-P
我们也可以这样做:
#include <iostream>
#include <cstdlib>
using namespace std;
int fnfoo(int inum){
cout << "I Love You" << endl;
return (exit(0),inum);
}
int dummy = fnfoo(5);
int main()
{
cout << "Love" << endl;
}
Run Code Online (Sandbox Code Playgroud)
简单而且工作完美;)
| 归档时间: |
|
| 查看次数: |
3316 次 |
| 最近记录: |