八.类的空间长度;this 指针概念;空指针访问成员函数;const 修饰成员函数 ;友元
1.Code
:
#include<iostream>
using namespace std;
class Person
{
public:
short a;
static int b;
Person()
{
a = 0;
}
void func()
{
cout << "a = " << this->a << endl;
}
static void func1()
{
cout << "b = " << b << endl;
}
};
int Person::b = 0;
class Person1
{
public:
Person1(int age)
{
this->age = age;
}
Person1& PersonAdd(Person1 P)
{
this->age += P.age;
return *this;
}
int age;
};
void test()
{
Person1 P1(10);
cout << "P1.age = " << P1.age << endl;
Person1 P2(10);
P2.PersonAdd(P1).PersonAdd(P1).PersonAdd(P1).PersonAdd(P1);
cout << "P2.age = " << P2.age << endl;
}
class Person2
{
public:
void show()
{
cout << " 函数 show " << endl;
}
void show_NULL()
{
if (this == NULL) { return; }
cout << a << endl;
}
public:
int a;
};
void test1()
{
Person2* P3 = NULL;
P3->show();
P3->show_NULL();
}
class Person3
{
public:
Person3()
{
a = 0;
b = 0;
}
void func() const
{
this->b = 100;
cout << "常函数" << endl;
cout << "b = " << b <<endl;
}
void func1()
{
cout << "正常函数" << endl;
}
public:
int a;
mutable int b;
};
void test2()
{
const Person3 Per1;
cout << "Per1.a = " << Per1.a << endl;
Per1.b = 162;
cout << "Per1.b = " << Per1.b << endl;
Per1.func();
}
class Myroom;
class sdf
{
public:
sdf();
void sdf_look();
private:
Myroom* myroo;
};
class Myroom
{
friend void friend1(Myroom * M_copy);
friend class F_L;
friend void sdf::sdf_look();
public:
int S = 1234;
private:
int D = 4321;
};
void friend1(Myroom* M_copy)
{
M_copy->S = 1235;
M_copy->D = 4320;
cout << "friend1 访问(公共) M_copy->S = " << M_copy->S << endl;
cout << "friend1 访问(私有) M_copy->D = " << M_copy->D << endl;
}
class F_L
{
public:
F_L()
{
myroom = new Myroom;
}
void look()
{
myroom->S = 1236;
myroom->D = 4321;
cout << "friend2 访问(公共) myroom->S = " << myroom->S << endl;
cout << "friend2 访问(私有) myroom->D = " << myroom->D << endl;
}
private:
Myroom* myroom;
};
sdf::sdf()
{
myroo = new Myroom;
}
void sdf::sdf_look()
{
myroo->S = 17;
myroo->D = 42;
cout << "friend3 访问(公共) myroom->S = " << myroo->S << endl;
cout << "friend3 访问(私有) myroom->D = " << myroo->D << endl;
}
void test3()
{
Myroom Myroom1;
friend1(&Myroom1);
F_L friend_lei;
friend_lei.look();
sdf friend_han;
friend_han.sdf_look();
}
int main()
{
cout << endl << endl << " 一. 类内 成员变量 与 成员函数 分开存储 " << endl << endl;
cout << " 只有非静态成员变量才占类的空间长度 " << endl;
cout << "sizeof(Person) = " << sizeof(Person) << endl;
cout << endl << endl << " 二. this 指针概念 " << endl << endl;
test();
cout << endl << endl << " 三.空指针访问(调用)成员函数 " << endl << endl;
test1();
cout << endl << endl << " 四. const 修饰成员函数 " << endl << endl;
test2();
cout << endl << endl << " 五. 友元" << endl << endl;
test3();
system("pause");
return 0;
}
2.运行结果
:
