this指针
关键字this包含“当前对象的地址”,即this指针的值为&object。
在 某个类的成员方法 调用 其他成员方法 时,编译器将隐式得传递this指针。
* 调用静态方法时,不会隐式得传递this指针(静态方法是所有实例共享的)。
* 要在静态方法里 使用非静态实例变量,应显示地声明一个形参,并将实参设置为this指针。
class A{
private:
int age;
void fun(string test){
cout << test;
}
public:
void use(){
fun("play this");
//等价于fun(this, "play this");
}
void set(int num){
this->age = num;
//等价于age = num;
}
};
友元
友元类和友元函数,可以从外部访问 类的私有数据成员和方法。友元类里的所有方法都能访问Human类的私有数据成员和方法。
#include <iostream>
#include <string>
using namespace std;
class Human{
private:
friend void DisplayAge(const Human& person); //声明友元函数
string name;
int age;
public:
Human(string humansName, int humansAge){
name = humansName;
age = humansAge;
}
};
void DisplayAge(const Human& person){ //定义友元函数
cout << person.age << endl; //友元函数访问类的私有成员
}
int main(){
Human firstMan("Adam", 25);
cout << "Accessing private member age via friend function: ";
DisplayAge(firstMan);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Human{
private:
friend class Utility; //声明友元类
string name;
int age;
public:
Human(string humansName, int humansAge){
name = humansName;
age = humansAge;
}
};
class Utility{ //定义友元类
public:
static void DisplayAge(const Human& person){
cout << person.age << endl; //友元类里使用类的私有成员属性
}
};
int main()
{
Human firstMan("Adam", 25);
cout << "Accessing private member age via friend class: ";
Utility::DisplayAge(firstMan);
return 0;
}