1、类对象作为类成员
#include <iostream>
#include<string>
using namespace std;
class Phone
{
public:
Phone(string pName)
{
cout << "Phone构造函数调用" << endl;
m_PName = pName;
}
~Phone()
{
cout << "Phone析构函数调用" << endl;
}
string m_PName;
};
class Person
{
public:
Person(string name, string pName) :m_Name(name), m_Phone(pName)
{
cout << "Person构造函数调用" << endl;
}
~Person()
{
cout << "Person析构函数调用" << endl;
}
string m_Name;
Phone m_Phone;
};
void test01()
{
Person p("张三", "苹果");
cout << p.m_Name << p.m_Phone.m_PName << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
2、静态成员访问权限
#include <iostream>
#include<string>
using namespace std;
class Person
{
public:
static void func()
{
cout << "func调用" << endl;
m_A = 100;
cout << m_A << endl;
}
static int m_A;
private:
static void func2()
{
cout << "func2的调用" << endl;
}
};
int Person::m_A = 0;
void test01()
{
Person p1;
p1.func();
Person::func();
}
int main()
{
test01();
system("pause");
return 0;
}
3、成员变量和成员函数分开储存
#include <iostream>
#include<string>
using namespace std;
class Person
{
int m_A;
static int m_B;
void func(){}
static void func(){}
};
void test01()
{
Person p;
cout << "size of p:" << sizeof(p) << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
4、this指针的用途
#include <iostream>
#include<string>
using namespace std;
class Person
{
public:
Person(int age)
{
this->age = age;
}
Person & PersonAddAge(Person &p)
{
this->age += age;
return *this;
}
int age;
};
void test01()
{
Person p1(18);
cout << p1.age << endl;
}
void test02()
{
Person p2(10);
Person p3(10);
p3.PersonAddAge(p2).PersonAddAge(p2);
cout << p3.age << endl;
}
int main()
{
test02();
system("pause");
return 0;
}
5、空指针访问成员函数
#include <iostream>
#include<string>
using namespace std;
class Person
{
public:
void showClassName()
{
cout << "this is Person class" << endl;
}
void showPersonAge()
{
if (this == NULL)
{
return;
}
cout << m_Age << endl;;
}
int m_Age;
};
void test01()
{
Person *p = NULL;
p->showPersonAge();
}
int main()
{
test01();
system("pause");
return 0;
}
6、const修饰成员函数
#include<iostream>
using namespace std;
class Person
{
public:
void showPerson() const
{
}
int m_A;
};
void test01()
{
const Person p;
p.showPerson();
}
int main()
{
system("pause");
return 0;
}