c++ - std::cout 的简约重新实现

标签 c++ c namespaces operator-overloading

你能帮我重新实现 std::cout 最基本的功能吗?

要求:

1) 可以包含C标准头文件,但不能使用C++库。例如stdio.h可用于printf函数。

2) 如果它只适用于一种类型也没关系,让我们使用“char*”。目标是找到最简单的实现。

3) 以下行应该无需任何修改即可工作(应使用命名空间):

std::cout << "Hello World!\n";

4) 所有内容都应该在一个文件中,包括 main() 方法

编辑:

这是我的代码,它会导致编译错误:

#include <stdio.h>

namespace std {
  class cout {
    public:
      void operator << (char* s) {
        printf("%s", s);
      }
  };
}

int main() {
  std::cout << "Hello World!\n"; // Compilation error: expected an identifier
}

谢谢

最佳答案

这是解决方案,您没有使用运算符引用对象,而是引用类类型。您需要创建该类型的对象才能使用 << 。

#include <stdio.h>

//don't ever use std namespace
namespace test {
    class base_cout {
    public:
        void operator << (const char const* s) {
            printf("%s",s);
        }
    };

    // This should be extern if you want to use it outside a single file.
    base_cout cout;
}

int main() {
    test::cout << "Hello World\n";
}

这就是 iostream header 中的 cout 的内容: namespace std { extern ostream __declspec(dllexport) cout; }

关于c++ - std::cout 的简约重新实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58890016/

相关文章:

c++ - 关于未声明 TITLEBARINFO 的 MinGW 错误

将 `while` 循环转换为 `for` 循环

c - 如何使用 ptrace 找到 CALL 和 RET 号码?

javascript - 包含 jquery 插件 (jlembed) 的问题。与 namespace 冲突

c++ - qpainter 绘画替代品(在 Mac 上性能很差)

c++ - 为什么 main() 的参数不是 const 限定的?

c++ - 我可以通过它的字节指定一个整数常量吗?

c++ - 从 char 指针中减去 char 数组产生一个 int?

c++ - 我应该使用静态还是命名空间?

python - 嵌套函数的名称是什么?为什么 eval 看不到嵌套函数?