📄 ex14.cpp
字号:
//第14章 迈入面向对象编程部分
//[例14.1]用结构实现求两个数的和(函数通过CA*const型的形参操作结构CA中的成员)
#include <stdio.h>
struct CA { int m;long n; };//声明一个结构CA,它有两个不同类型的数据成员
inline void Initial(CA*const p,int x,int y) { p->m=x;p->n=y;}//全局函数初始化结构成员
inline int Add(CA*const ths) { return ths->m+ths->n;}//全局函数Add返回成员之和
void Show(CA*const pthis) { printf("%d,%d,%d\t",pthis->m,pthis->n,Add(pthis));}
void main() //在全局函数Show中调用Add(CA*const)全局函数
{ CA b={10,20}; Show(&b); //定义结构变量b并初始化,然后显示数据
Initial(&b,1,2); //调用全局函数void Initial(CA* const,int ,int );
Show(&b); //调用全局函数Show(CA* const );
} // 输出: 10,20,30 1,2,3
// [例14.2]用类的形式(将含CA*const形参的全局函数变为成员函数)实现求两个数的和
#include <stdio.h> //this是一个隐含的形参,此时类型属性为CA* const
class CA //CA是用户引入的类类型名
{ public:int m;long n; //声明两个公共的数据成员
public: int Add(){ return this->m+ this->n; } //内置定义成员函数Add
void Initial(int x,int y) { m=x; n=y;}//内置定义成员函数Initial
void CA:: Show() ; //声明成员函数Show
}; //在成员函数Show中调用Add()成员函数
void CA:: Show() { printf("%d,%d,%d\t",m,n,Add());}//在类的外面定义成员函数Show
void main() //初始化[CA b={10,20};]形式对于只有公共成员的类或结构才有效
{ CA b={10,20}; b.Show(); //定义局部对象b并初始化,然后显示数据
b.Initial(1,2); //局部对象b调用成员函数void CA::Initial(int ,int );
b.Show(); //局部对象b调用成员函数void CA::Show();
} // 输出: 10,20,30 1,2,3
// [例14.3]内部访问和外部访问。通过指针p可轻易地间接访问内部的私有成员
#include <stdio.h>
class CType
{ private: int m_n;
public: CType& Set(const CType& r,int n); // const对象引用入口,对象引用返回
int* Initial(int n) //返回int*型的指针的成员函数
{ this->m_n=n; //在成员函数中访问私有成员m_n
return &m_n; //返回私有数据成员this->m_n的地址
} //成员函数或友元函数可访问类中所有的成员
};
CType& CType::Set(const CType& r,int n)// const CType&形参r说明r.m_n作为右值
{ static CType a; //定义静态局部对象a
a.m_n=n; //静态局部对象a访问私有成员m_n
if(n==1) return a; //n=1返回静态局部对象a
m_n=n+r.m_n; //引用形参r访问私有成员m_n
return *this; // return *this返回调用该成员函数的对象
}//this此时是属性为CType*const型的指针,间接对象*this是CType型左值
CType b; //定义全局对象b。
int *p=b.Initial(20); //对象b在外部访问公共的成员函数Initial
void main() //b.Initial(20)完成p=&b.m_n,但b.m_n访问私有成员是错误的。
{ printf("%d\t",*p);// *p是b.m_n的间接变量,指针间接访问私有成员m_n。
b=b.Set(b,2); printf("%d\t",*p); printf("%d\t",*b.Initial(30));
} // 输出: 20 22 30
////////// [例14.4]内联成元函数破除私有封装
#include<string.h>
#include<stdio.h>
typedef struct tagPOINT { long x; long y; } POINT;
class CPoint
{public:inline long& X() ; //返回long&型引用的函数X()
inline long GetY() ; //返回long型数值的函数GetY()
private: long x; long y;
}; //内联成员函数的定义一般应放置在调用点之前
inline long& CPoint::X() { return x;}
inline long CPoint::GetY() { return y;}
void main()
{ POINT s={10,20}; //仅存在公共成员才采用集合类型的初始化格式
CPoint r; //存在私有数据成员的类不采用结构中的初始化语法
memcpy(&r,&s,sizeof(r)); //通过内存拷贝函数完成对象的初始复制
printf("%d,%d\n",r.GetY(), r.X()+=r.GetY());//输出: 20,30
} //函数调用r.X()构成左值,而r.GetY()是右值表达式。
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -