VC6.0对友元的支持问题

VC6.0对友元支持的不好,将友元函数定义在类体外时总是报没有权限访问私有成员,将友元函数放入类体中就可以访问了,如下:

#include <iostream>
using namespace std;
class MyString
{
public:
	MyString(char *ptr=NULL);
	~MyString();
	friend ostream& operator<<(ostream& out, MyString &str)
	{
		if (str.m_data != NULL)
			out << str.m_data;
		return out;
	}


private:
	char* m_data;
};


MyString::MyString(char *ptr)
{
	if (ptr == NULL)
	{
		m_data = new char[1];
		*m_data = '\0';
	}
	else
	{
		int nLen = strlen(ptr);
		m_data = new char[nLen+1];
		strcpy(m_data, ptr);
	}
}


MyString::~MyString()
{
	delete m_data;
}


/*
ostream& operator<<(ostream& out, MyString &str)
{
	if (str.m_data != NULL)
		out << str.m_data;
	return out;
}
*/


int main()
{
	MyString str("Hello");
	cout << str << endl;
	MyString str2;
	cout << str2 << endl;
	return 0;
}

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页