简体   繁体   English

在命名空间中调用void函数的C ++错误

[英]C++ error to call void function in namespace

I just started learning c++ and got an error while doing practicing. 我刚开始学习c ++,却在练习时出错。 I was practicing using namespace and cin, cout. 我正在练习使用名称空间和cin,cout。

I tried to print out the function of each namespace by each input. 我试图通过每个输入打印出每个名称空间的功能。 Here below is the code I wrote : 下面是我写的代码:

#include "iostream"

using namespace std;

namespace ns1
{
    int pp()
    {
        int x = 1;
        for (int i = 0; i < 9; i++)
        {
            cout << x << endl;
            x++;
        }
        return 0;
    }
}
namespace ns2
{
    void pp()
    {
        double x = 2;
        while (x < 6)
        {
            cout << x << endl;
            x += 1.7;
        }
    }
}
int main()
{
    bool check = 0;
    cout << "Type 0 or 1 then you will have the following answer" << endl;
    cin >> check;
    if (check == 0)
    {
        cout << ns1::pp() << endl;
    }
    else
    {
        cout << ns2::pp() << endl;
    }
    return 0;
}

I don't know why void pp() cannot be printed out. 我不知道为什么不能打印出空pp()。

Could anyone let me know why it happens? 谁能让我知道为什么会这样吗?

First, let's reduce the problem to a MCVE and remove as much noise as possible from the program. 首先,让我们将问题简化为MCVE并从程序中消除尽可能多的噪声。

#include <iostream>
void pp()
{
}

int main()
{
    std::cout << pp();
}

This produces the exact same error with no namespaces or other distractions. 这会产生完全相同的错误,而没有名称空间或其他干扰。

The crux of the problem is pp returns void , that is nothing, from the function. 问题的症结在于pp从函数返回void ,即为void Since nothing is returned, there is nothing to output. 由于未返回任何内容,因此没有任何输出。

Because writing an output function that outputs nothing is essentially wasted programmer time, no one has seen fit to specify that standard library implementors must implement an operator<< that handles void . 因为编写一个不输出任何内容的输出函数实际上是在浪费程序员时间,所以没有人认为可以指定标准库实现者必须实现一个用于处理voidoperator<< As Justin points out in the comments below you can't use void as a function parameter because variables of type void cannot be instantiated. 正如贾斯汀在下面的注释中指出的那样,您不能将void用作函数参数,因为void类型的变量无法实例化。 This makes it not just a waste of time but impossible. 这不仅浪费时间,而且是不可能的。

You will find you will have a similar problem with custom classes. 您会发现自定义类也会遇到类似的问题。 Unless someone has taken the time to write a << overload for the class, the class cannot be printed unless it can first be converted into a class or datatype that can be printed. 除非有人花时间为该类编写<<重载,否则该类将无法打印,除非可以先将其转换为可以打印的类或数据类型。

In the case of Standard Library containers there is no agreed upon default way a container should be output, so there are no built-in << overloads for the library containers. 对于标准库容器,没有商定默认的容器输出方式,因此库容器没有内置的<<重载。 This is often a shock the first time you try to print a std::vector . 第一次尝试打印std::vector时,通常会感到震惊。

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

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