使用和不使用using namespace std;一个小程序,不明白
#include <iostream.h>
//就是这第一行,如果改为
//#include <iostream>
//using namespace std;
//就会出错,错误代码(最后)
class Date
{
public:
Date(int m=1,int y=0):month(m),year(y){}
void Print(){cout<<month<<"/"<<year<<endl;}
friend Date operator+(const Date& d1,const Date& d2);
private:
int month,year;
};
/*错误代码:
e:\processfiles\cpp2rank\virtual225\main.cpp(9) : fatal error C1001: INTERNAL COMPILER ERROR
(compiler file 'msc1.cpp', line 1786)
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
Error executing cl.exe.
virtual225.exe - 1 error(s), 0 warning(s)
*/
Date operator+(const Date& d1,const Date& d2)
{
int year,month;
year=d1.year+d2.year;
month=d1.month+d2.month;
year+=(month-1)/12;
month=(month-1)%12+1;
return Date(month,year);
}
void main()
{
Date d1(3,2004),d2,d3(10);
d2=d3+d1;
d2.Print();
}
参考答案:名字空间的问题
//#include <iostream.h>
#include <iostream>
//==================
using std::cout;
using std::endl;
//==================
class Date
{
public:
Date(int m=1,int y=0):month(m),year(y){}
void Print(){cout<<month<<"/"<<year<<endl;}
friend Date operator+(const Date& d1,const Date& d2);
private:
int month,year;
};
Date operator+(const Date& d1,const Date& d2)
{
int year,month;
year=d1.year+d2.year;
month=d1.month+d2.month;
year+=(month-1)/12;
month=(month-1)%12+1;
return Date(month,year);
};
void main()
{
Date d1(3,2004),d2,d3(10);
d2=d3+d1;
d2.Print();
}