1?編程練習(xí)一
????????這一部分介紹C++友元函數(shù)、友元類和this指針。文章來源:http://www.zghlxwxcb.cn/news/detail-823962.html
1.1?友元函數(shù)
????????友元函數(shù),可以在類的成員函數(shù)外部直接訪問對象的私有成員。文章來源地址http://www.zghlxwxcb.cn/news/detail-823962.html
1.1.1?設(shè)計代碼
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
class CCar;//提前聲明CCar類,以便后面的CDriver類使用
class CDriver
{
public:
void ModifyCar(CCar* pCar);//改裝汽車
};
class CCar
{
private:
int price = rand() % 1000;
//聲明友元
friend int MostExpensiveCar(CCar cars[], int total);
//聲明友元
friend void CDriver::ModifyCar(CCar* pCar);
};
void CDriver::ModifyCar(CCar* pCar)
{
for (int i = 0; i < 5; i++)
{
pCar->price += 1000;//汽車改裝后價值增加
pCar++;
}
}
int MostExpensiveCar(CCar cars[], int total)
{
//求最貴汽車的價格
int tmpMax = -1;
for (int i = 0; i < total; i++)
{
cout << cars[i].price << " ";
if (cars[i].price > tmpMax) {
tmpMax = cars[i].price;
}
}
cout << endl;
return tmpMax;
}
int main()
{
srand(time(NULL));
CCar cars[5];
int tmpMax;
tmpMax = MostExpensiveCar(cars, 5);
cout << tmpMax << endl;
CDriver c;
c.ModifyCar(cars);
tmpMax = MostExpensiveCar(cars, 5);
cout << tmpMax << endl;
return 0;
}
1.1.2?執(zhí)行結(jié)果

到了這里,關(guān)于C++語言程序設(shè)計之類和對象進階(3)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!