简体   繁体   中英

C++ and Visual Studio error - no suitable conversion function from “std::basic_ostream<char, std::char_traits<char>>” to “int” exists

Visual Studio is going crazy on me recently, and gives me the error in the subject when all I did was a simple cout...

CODE:

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

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

using namespace std;

int main{
    cout << "hi";
}
 int main{ cout << "hi"; } 

Due to the possibility of initialising objects in C++ with the {} syntax, your compiler probably interprets this code as an attempt to create a global int variable called main , initialised with the result of std::ostream::operator<< , a member function which returns a reference to the std::ostream itself.

It's as if you had written:

double some_variable { cout << "hi" }

Or:

double some_variable { cout }

std::ostream is actually std::basic_ostream<char, std::char_traits<char>> . And that type is not compatible with int .

The only thing which is strange is why the ; after "hi" does not immediately cause the compiler to stop trying; but you don't say which compiler version and which options you are using.

In any case, all of those facts finally result in the error message:

 no suitable conversion function from “std::basic_ostream<char, std::char_traits<char>>” to “int” exists 

and in:

Also, the semicolon after "hi" is highlighted, and says "expected a }"

Solution: make main a function:

int main() {
    cout << "hi";
}

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