简体   繁体   中英

c++ function does not take 0 arguments

Why am I getting this error from the compiler about the function not taking 0 arguments? Is is because I declare the function after it has been called?

// HelloWorld.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>


using namespace std;

int main()
{
    cout << "Hello World!\n";
    cout << "Game over!\n";
    swap();
    system("pause");
    return 0;
}

int swap()
{
    int on = 1;
    int off = 0;
    int temp = on;
    on = off; 
    off = temp;
    return 0;
}

在此处输入图片说明

Is is because I declare the function after it has been called?

Yes.

By the time the compiler sees the call to swap() , it doesn't know about your function yet. You'd normally get an error along the lines of “call to undeclared function” in this case, were it not for std::swap (which takes two arguments) that you've pulled into your name-space by the using namespace std directive.

In order to fix: Move the definition of swap above main (as a function definition is always also a function declaration) or leave it where it is an put a dedicated declaration

int swap();

above main . I'd also get rid of the using namespace std; as it, as you can see, might do you more harm than good and instead prefix all standard-library types and functions explicitly with std:: . But that's not mandatory and also not the root cause of your current issue.

尝试在main之上定义函数或只在main之上声明。它现在从.net库调用swap

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