对象能不能直接访问私有成员?分两种情况,如果是在类(包括友元类)内定义的对象,可以,在类外,不行。
举个简单的例子
#include<iostream>
using namespace std;
class Boat;
class Car;
class Boat{
private:
int weight;
public:
Boat(int a){
weight = a;
}
int getweight(){return weight;}
friend int totalweight(Boat &a, Car &b);
};
class Car{
private:
int weight;
public:
Car(int a){
weight = a;
}
int getweight(){return weight;}
friend int totalweight(Boat &a, Car &b);
};
int totalweight(Boat &a, Car &b){//
return a.weight+b.weight;
}
int main()
{
Boat a(10);
Car b(20);
cout<<totalweight(a, b);
return 0;
}
注意totalweight函数中的形参a,b可以直接访问私有成员,如果在声明totalweight函数时不描述形参呢,如下面这样
friend int totalweight();
编译报错
因为a,b均在类外定义,所以无法直接访问类的私有成员,但可以通过成员函数访问
int totalweight(Boat &a, Car &b){
return a.getweight()+b.getweight();
}
同理,在main函数中定义的对象也无法直接引用私有成员。
初学者的一点看法,如有问题欢迎指正