1. 对象模型和this指针
在这里插入代码片:
#include<iostream>
using namespace std;
#include <string>
class Person
{
int a;
static int b;
void func() {}
static void func2() {}
};
int Person :: b=0;
void test01()
{
Person p;
cout << "size of p(一个空类) " <<sizeof(p) << endl;
}
void test02()
{
Person p;
cout << "size of p的大小为: " <<sizeof(p) << endl;
}
int main()
{
test02();
}
2. this指针概念
在这里插入代码片:
#include<iostream>
using namespace std;
#include <string>
class Person
{
public:
int age;
Person(int age)
{
this->age = age;
}
Person& PersonAddAge(Person &p)
{
this->age += p.age;
return *this;
}
};
void test01()
{
Person p(18);
cout << "p1的年龄为 : " <<p.age << endl;
}
void test02()
{
Person p1(11);
Person p2(10);
p2.PersonAddAge(p1).PersonAddAge(p1);
cout << "p2的年龄为 : " <<p2.age << endl;
}
int main()
{
test01();
test02();
}
3.空指针访问成员变量函数
在这里插入代码片:
#include<iostream>
using namespace std;
#include <string>
class Person
{
public:
void showClassName()
{
cout << "this is Person 类" << endl;
}
void showPersonAge()
{
if(this==NULL)
{
return;
}
cout << "age= " << this->m_age<< endl;
}
int m_age;
};
void test01()
{
Person *p=NULL;
p->showClassName();
p->showPersonAge();
}
int main()
{
test01();
}
4.const修饰成员函数
在这里插入代码片:
#include<iostream>
using namespace std;
#include <string>
class Person
{
public:
void showPerson() const
{
n_age=100;
}
void func();
int m_age;
mutable int n_age;
};
void test01()
{
Person p;
p.showPerson();
}
void test02()
{
const Person p;
p.n_age=100;
p.showPerson();
}
int main()
{
test01();
}
|