简体   繁体   中英

C++ error to call void function in namespace

I just started learning c++ and got an error while doing practicing. I was practicing using namespace and 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.

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.

#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. 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 . 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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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