马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
三个简单的文件捣鼓了半天发现是友元函数出错了(友元函数在类中定义时没出错)//stringbad.cpp
#include "stringbad.h"
#include <cstring>
using namespace str;
int stringbad::string_num=0;
stringbad::stringbad()//default constructor
{
ptr=new char[5];
length=4;
strcpy(ptr,"c ++");
string_num++;
}
stringbad::stringbad(const char *p)
{
length=strlen(p);
ptr=new char[length+1];
strcpy(ptr,p);
string_num++;
}
stringbad::~stringbad()
{
string_num--;
delete [] ptr;
}
ostream &operator<<(ostream &os,stringbad &st) //友元函数的定义
{
cout <<"123";
return os;
}
//stringbad.h
#ifndef STRINGBAD_H
#define STRINGBAD_H
#include <iostream>
namespace str
{
using namespace std;
class stringbad
{
private:
char * ptr;
int length;
static int string_num;
public:
stringbad(const char *p);
stringbad();
~stringbad();
friend ostream &operator<<(ostream &os,stringbad &st);//友元函数的声明,但如果在这里一起定义的话就不出错
};
}
#endif // STRINGBAD_H
//main.cpp
#include <iostream>
#include "stringbad.h"
using namespace str;
int main()
{
stringbad a;
cout <<a;
return 0;
}
大神们帮我解释一下,也有可能是我编译器问题 |