开发者

expected constructor, destructor, or type conversion before '<<' token

开发者 https://www.devze.com 2023-03-27 01:45 出处:网络
On Compiling follow programs using g++. #include<iostream> using namespace std; cout<<\"Before Main\"<<endl;开发者_运维技巧

On Compiling follow programs using g++.

#include<iostream>
using namespace std;

cout<<"Before Main"<<endl;开发者_运维技巧

int main()
{
cout<<"Within Main"<<endl;
}

Errors: expected constructor, destructor, or type conversion before '<<' token. So may i know how to fixe this. What's the reason for getting erros.


You cannot execute statements outside a function.


You cannot put non-declaration statements at namespace scope.

However, an expression statement can be converted to a declaration, e.g.

bool const bah = (cout<<"Before Main"<<endl);

It is generally not a good idea, but perhaps worth knowing about?

Cheers & hth.,


Such statements cannot be executed without putting it inside a function body. If you want something before main(), then encapsulate it in a global struct and define an object.

struct Print {
  Print() { cout<<"Before Main"<<endl; }
  ~Print() { cout<<"After Main"<<endl; }
} print;                        // <--- declare/define object

int main()
{
  cout<<"Within Main"<<endl;
}


It is illegal, everything what will be execute must be inside main function. Of course you can write second function, and there put cout<<"Before Main"<<endl;, but main will be execute firstly. you can write :

#include<iostream>
using namespace std;
void f() {
   cout<<"Before Main"<<endl;
}

int main()
{
   f();
   cout<<"Within Main"<<endl;
}

But main is first function which will be executed.

0

精彩评论

暂无评论...
验证码 换一张
取 消