1. 程式人生 > >友元函式過載操作符

友元函式過載操作符

當使用namespace std的時候會出現訪問不了私有成員的錯誤,不使用std便沒有錯誤。奇怪的是之前的程式使用的std也沒有錯誤,不知為何 

#ifndef STRING_H_
#define STRING_H_
#include <iostream>
//using namespace std;   error C2248: 'str' : cannot access private member declared in class 'Strin'

class Strin
{
private:
	char *str;                                       //pointer to string
	int nLen;                                        //length of string
	static int nStringNumbers;                       //number of objects
	static const int CINLIM;
public:
	Strin(char *s);                                 //一般構造器 String str("zhaonan");
	Strin();                                        //預設構造器
	Strin(Strin & st);                             //複製構造器
	~Strin();                                       //解構函式
	int nLength(){return nLen;}

	//過載操作符
	Strin & operator= (Strin & a);                 //賦值
	Strin & operator= (char *c);
	char & operator[] (int i);

    friend	bool operator < (Strin &a, Strin &b);
    friend	bool operator > (Strin &a, Strin &b);          //比較兩個字串的大小
    friend	bool operator == (Strin &a, Strin &b);         //判斷兩個字串是否相等

    friend	std::ostream & operator << (std::ostream & os, Strin & st);//讀操作,顯示字串
    friend	std::istream & operator >> (std::istream & is, Strin & st);//寫操作,更新字串內容


	static int HowMany();
};
#endif