1.成员变量和成员函数分开存储
一句话,只有非静态成员变量属于类对象上
2.this指针
this指向的调用成员函数的类对象
this指针一般有两个用途
防止名称冲突
类内返回对象本身
#include <iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
this->age = age;
}
Person& AddAge(Person p)
{
this->age += p.age;
return *this;
}
int age;
};
int main()
{
Person p1(10);
Person p2(10);
p2.AddAge(p1).AddAge(p1);
cout << p2.age << endl;
}
Person& AddAge(Person p)
{
this->age += p.age;
return *this;
}需用引用返回,不能值返回,前面说过拷贝构造函数的三个调用时机
其中之一就是值返回
如果我们没有自己写拷贝构造函数,就会默认值拷贝
除第一次p2.age会加一次,后面都是创建新的对象,进行函数调用
3.空指针访问成员函数
空指针是能访问成员函数的,可能不同的编译器会报错把,但是语法上是可行的
但是有一种情况要避免,上面的this指针指向的是调用成员函数的类对象,如果对象为空,
那么是肯定访问不到里面的变量的,所以优化了一下
#include <iostream>
using namespace std;
class Person
{
public:
void show()
{
if (this == NULL)
{
return;
}
cout << this->age << endl;
}
int age;
};
int main()
{
Person* p=NULL;
p->show();
}
4.const修饰成员函数
class Person
{
//this本质 Person *const 对象名
void show() const 常函数
{
this->a=100;//不可以修改
this->b=100;//可修改
}
void haha()
{
}
int a;
mutable int b;
};
int main()
{const Person p;//常对象
常对象只能调用常函数
p.show();//可以
p.haha();//不可以,因为普通成员函数是可以修改成员变量的
}
友元
友元的目的 :让一个函数或类访问另一个类中的私有成员
1.全局函数作友元
#include <iostream>
using namespace std;
class Person
{
friend void visit(Person* p);//全局函数作友元
public:
Person()
{
height = 180;
weight = 60;
}
public:
int height;
private:
int weight;
};
void visit(Person *p)
{
p->weight = 200; //可访问Person类中私有属性,并修改
cout << p->height << endl;
cout << p->weight << endl;
}
void test()
{
Person p1;
visit(&p1);
}
int main()
{
test();
}
在类内声明 friend + 函数声明
2.类作友元
这个与上面的操作类似
可以将类内函数在类外实现;如果一个类中的成员函数要访问另一个未实现的类
需提前声明 class 类名;
#include <iostream>
using namespace std;
class Phone;
class Person
{
public:
Person();
void visit();
Phone* phone;
};
class Phone
{
friend class Person;
public:
Phone();
public:
string name;
private:
string add;
};
Phone::Phone()
{
name = "小米";
add = "北京";
}
Person::Person()
{
phone = new Phone;
}
void Person::visit()
{
cout << phone->name << endl;;
cout << phone->add;
}
void text()
{
Person p;
p.visit();
}
int main()
{
text();
}
3.成员函数作友元
同上差不多
friend class Phone ; 类作友元
friend void Phone visit();成员函数作友元