欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

OJ:重载 << 运算符

程序员文章站 2022-06-28 18:18:06
Description 补足程序,使得下面程序输出的结果是: 100 ~~~~ include include using namespace std; // Your Code Here string Print1() { return " "; } int Print2() { return 1 ......

Description

补足程序,使得下面程序输出的结果是:

****100

#include <iostream>
#include <string>
using namespace std;
// Your Code Here
string Print1() 
{
    return "****";  
}
int Print2() 
{
    return 100; 
}

int main()
{
    cout << Print1 << Print2 << endl; 
    return 0;
}

Output

****100

解法如下:

#include <iostream>
#include <string>
using namespace std;

ostream& operator<<(ostream& out, string (*p)())
{
    out << (*p)();
    return out;
}

ostream& operator<<(ostream& out, int (*p)())
{
    out << (*p)();
    return out;
}

string Print1() 
{
    return "****";  
}
int Print2() 
{
    return 100; 
}

int main()
{
    cout << Print1 << Print2 << endl; 
    return 0;
}