#include<iostream> #include<string> using namespace std; class animal { string name; int age; public: animal(string name,int age=0) { this->name=name; this->age=age; } animal& operator+(animal& a); friend ostream& operator <<(ostream& os,animal& a); }; ostream& operator<<(ostream& os,animal& a) { os<<a.age<<endl; os<<a.name<<endl; return os; } animal& animal::operator +(animal& a) { age+=a.age; return *this; } int main() { animal a("cat",33); animal b("dog",32); cout<<a; cout<<a+b<<endl; return 0; } 首先来看一下这段代码,应该说代码是没有任何问题肯定能通过编译的,但是在VC 6.0下确实通不过。这是为什么呢? 代码在VC6.0中不能被编译通过:提示不能访问私有成员,没有这个访问权限。 改成这样就可以了,代码如下: #include<iostream> #include<string> using namespace std; class animal; ostream& operator <<(ostream& os,animal& a); class animal { string name; int age; public: animal(string name,int age=0) { this->name=name; this->age=age; } animal& operator+(animal& a); friend ostream& operator <<(ostream& os,animal& a); }; ostream& operator<<(ostream& os,animal& a) { os<<a.age<<endl; os<<a.name<<endl; return os; } animal& animal::operator +(animal& a) { age+=a.age; return *this; } int main() { animal a("cat",33); animal b("dog",32); cout<<a; cout<<a+b<<endl; return 0; } 原因: 这据说是VC的一个经典BUG。和namespace也有关. 只要含有using namespace std; 就会提示友员函数没有访问私有成员的权限。 解决方法:去掉using namespace std;换成更小的名字空间。 例如: 含有#include <string>就要加上using std::string 含有#include <fstream>就要加上using std::fstream 含有#include <iostream>就要加上using std::cin; using std::cout; using std::ostream; using std::istream; using std::endl; 等等,需要什么即可通过using声明什么. 下面给出解决办法: //方法一: 02//提前声明 03class cylinder; 04istream &operator>>(istream& is,cylinder &cy); 05 06//方法二: 07//不用命名空间 或者 像晨雨那样写 08#include<iostream.h> //方法三: 11 12class cylinder 13{ 14 friend istream &operator>>(istream& is,cylinder &cy)//写在类里面 15 { 16 cout<<"input length:"<<endl; 17 is>>cy.length; 18 cout<<"input width:"<<endl; 19 is>>cy.width; 20 cout<<"input height:"<<endl; 21 is>>cy.height; 22 return is; 23 24 } 25.......... 26 27//方法四:打SP6补丁,貌似不好使。。。(呵呵,是貌似也没用) 28 29//方法五:换别的对标准C++支持好的编译器,如DEV C++/。。。(呵呵) 对于解决办法参考了一些网上的资料,希望对大家能有所帮助!