#include <bits/stdc++.h>
using namespace std;
class Phone
{
public:
Phone(string pName)
{
m_Pname = pName;
cout << "Phone的构造函数" << endl;
}
~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 test()
{
Person p("张三","华为Mate40ProPlus");
cout << p.m_Name << "拿着:" << p.m_Phone.m_Pname << endl;
}
int main()
{
test();
return 0;
}
注意析构函数与构造函数的顺序
#include <bits/stdc++.h>
using namespace std;
class Person
{
public:
static void fun()
{
m_A = 100; //静态成员函数可以访问,静态成员变量
//m_B = 200; //错误,无法区分属性
cout << "static void fun()的调用" << endl;
}
static int m_A;
int m_B;
//静态成员函数有访问权限
};
int Person::m_A = 0;
void test()
{
//1.通过对象访问
Person p;
p.fun();
//2.通过类名访问
Person::fun();
}
int main()
{
test();
return 0;
}
#include <bits/stdc++.h>
using namespace std;
class Person
{
int m_A; //非静态成员变量 属于类上对象
static int m_B; //静态成员变量 不属于类上对象
void fun() //非静态成员函数 不属于类上对象
{
}
static void func() //静态成员函数 不属于类上对象
{
}
};
int Person::m_B = 0;
int main()
{
/*Person p;
//空对象占用内存空间为1
//C++编译器会给每一个空对象分配一个字节空间,是为了区分空对象占内存的位置
//每个空对象也应该有一个独一无二的内存地址
cout << "size of p :" << sizeof(p) << endl;*/
Person p;
cout << "size of p :" << sizeof(p) << endl;
return 0;
}
#include <bits/stdc++.h>
using namespace std;
class Person
{
public:
Person(int age)
{
//this指针指向被调用的成员函数所属的对象
this->age = age;
}
int age;
Person& PersonAddAge(Person &p)
{
this->age += p.age;
return *this;
}
};
void test1()
{
Person p1(18);
cout << "p1的年龄为:" << p1.age << endl;
}
void test2()
{
Person p1(10);
Person p2(10);
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
cout <<"p2的年龄为:" << p2.age <<endl;
}
int main()
{
//test1();
test2();
return 0;
}
#include <bits/stdc++.h>
using namespace std;
class Person
{
public:
void showClassName()
{
cout << "this is Person class" << endl;
}
void showPersonAge()
{
//报错原因是传入的指针是NULL
if(this == NULL)
{
return;
}
cout << "Age = " << this->m_Age << endl;
}
int m_Age;
};
void test()
{
Person *p = NULL;
p->showClassName();
p->showPersonAge();
}
int main()
{
test();
return 0;
}