C++ string中友元函数重载的问题

来源:百度知道 编辑:UC知道 时间:2024/04/30 12:35:45
本人C++初学者,在vc6中不是说友元函数的重载要用<iostream.h>的形式,不可以用<iostream> using namespace std;的形式吗?那么我如果想用字符串常量的话不是要包含<string>(不可以是<string.h>)吗?那如果我想用字符串常量,又要用友元函数的重载,应该怎么样?
好像这个就编不过去?
#include<iostream>
using namespace std;
class complex
{public:
complex(){real=0,imag=0;}
complex(double r,double i) {real=r,imag=i;}
friend complex operator + (complex &c1,complex &c2);
void display();
private:
double real;
double imag;
};

complex operator + (complex &c1,complex &c2)
{return complex(c1.real+c2.real,c1.imag+c2.imag);}

void complex::display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;}

int main()
{complex c1(1,2),c2(3,4),c3;
c3=c1+c2;
c3.display();
return 1;
}

在vc6中不是说友元函数的重载要用<iostream.h>的形式,不可以用<iostream> using namespace std;的形式吗?这句话不对,可以用.

#include <iostream>
#include <string>
using namespace std;

const string cr="string";

class weapen
{
friend ostream& operator<<(ostream& op,const weapen w)
{
op<<cr<<endl;
return op;
}
};

void main()
{
weapen w;
cout<<w;
}

友元是语言概念,iostream 和 iostream.h都只是库文件,他们也要靠编译器对语言的支持来实现,只要编译器支持,不管包含不包含那些文件,都是可以的,iostream.h的存在是为了向后兼容,另外,vc6对友元和模版的支持都并不太好。

string和string.h是2个不同的文件,C的string.h包含的是一些对C风格字符串常用操作的库函数,而string则是C++标准模板库的一部分,是以类和模板共同构件起来的,对字符串操作的类的封装。C的string.h文件扩充在C++中,名为cstring,string.h的存在同样是为了向后兼容(以C++编译器的口气来说...)。

要怎么写include的话,这样好了:

#include <iostream> // C++标准I/O
#include <string> // STL string类
#include <cstring> // string.h的C++别名
using namespace std;