为什么不使用命名空间STD和使用命名空间STD时宏的行为不同?

why is macro acting different while not using namespace std and while using namespace std?

本文关键字:命名空间 STD 为什么不      更新时间:2023-10-16

在下面的代码中宏1总是好的

but, 宏2 不工作,如果语句1没有写,为什么会发生这种情况?

#include<iostream>
#include<conio.h>
//using namespace std;      //--statement 1
#define l std::cout<<       //--macro 1
#define nl std::cout<<endl; //--macro 2
int main(){
      l "testing";  
      nl  // this is not working if i dont use statement 1 
      l "a new line";
getch();
return 0;
}

语句1未写入宏2产生错误,指出'[error]endl未在此范围内声明'

如果cout<<std::cout<<的短版本,这个错误应该不会发生…

这不是你的MACRO的问题。

endl对象也属于std名称空间,因此您应该使用

std::cout << std::endl;

using namespace std;
cout << endl;