gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:57:30 25 4
gpt4 key购买 nike

你能帮我重新实现 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com