繁体   English   中英

从方法调用时 C++ endl 不打印新行

[英]C++ endl not printing new line when called from a method

C++ 的新手我的理解是 endl 将添加一个新行。 因此,使用以下代码:

#include <iostream>

using namespace std;

void printf(string message);

int main()
{

cout << "Hello" << endl;
cout << "World" << endl;

printf("Hello");
printf("World");

return 0;

}

void printf(string message) {
cout << message << endl;
}

我希望 output 是:

你好

世界

你好

世界

但是,奇怪的是,output 是:

你好

世界

你好世界

看起来,当从用户定义的方法调用时, endl 没有添加新行..?? 我在这里的理解有什么问题。 请指教。

问题是由于重载解决方案,内置printf function 被选择在您自定义的printf ZC1C425268E1838A. 这是因为字符串文字"Hello""World"由于类型衰减衰减const char* ,并且内置的printf function 比您自定义的printf更匹配。

解决此问题,请将printf调用替换为:

printf(std::string("Hello"));
printf(std::string("World"));

在上述语句中,我们明确使用std::string的构造函数从字符串文字"Hello""World"创建std::string对象,然后将这些std::string对象按值传递给您的printf function .

另一种选择是将您的自定义printf放在自定义命名空间中。 或者,您可以将 function 命名为printf本身。

它使用内置的 printf 方法。 尝试显式使用 std::string 以便它调用自定义 printf 方法。

printf(std::string("Hello"));
printf(std::string("World"));

或者您可以将您的方法放在不同的命名空间中:

#include <iostream>

namespace test
{
    extern void printf(const std::string& message);
}

int main()
{
    std::cout << "Hello" << std::endl;
    std::cout << "World" << std::endl;

    test::printf("Hello");
    test::printf("World");

    return 0;

}

void test::printf(const std::string& message) {
    std::cout << message << std::endl;
}

您应该选择 function 名称而不是 printf(); 像“打印()”。

尝试将“printf”function 重命名为“print”,它可以正常工作-

#include <iostream>
using namespace std;
void print(string message);

int main()
{

cout << "Hello" << endl;
cout << "World" << endl;

print("Hello");
print("World");
cout <<endl;
return 0;

}

void print(std::string message) {
cout << message << endl;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM