c++友元函数程序改正

c++友元函数程序改正,第1张

测试过没有问题,

#include<iostream>

#include<cmath>

using namespace std

class point{

private:

int h

int l

public:

point(int a, int 橘旁烂b)

~point()

friend int distance(point &op, point &圆漏od)

}

point::point(int a = 0, int b = 0){

h = a

l = b

}

point::~point(){}

int distance(point &op, point &od){

int distance = 0

distance = pow(op.h - od.h, 2) + pow(op.l - od.l, 2)

return sqrt(distance)

}

int main()

{

point op1(1, 2)

point od2(2, 3)

point od3(2, 1)

double pr=distance(&op1, &od2)// 调用友启镇元函数演示

cout << pr << endl

return 0

}

----------Cyclinder.h----------#ifndef CYCLINDER_H#define CYCLINDER_Hclass Cylinder{public: friend double volume(const Cyclinder&c)firend double surfac(const Cyclinder&c)Cyclinder()Cyclinder(double radius,double height)private: double radiusdouble height}#endif----------Cyclinder.cpp----------#include"Cyclinder.h"Cyclinder::Cyclinder():radius(0),height(0){}Cyclinder::Cyclinder(double radius,double height):radius(radius),height(height){}double volume(const Cyclinder&c){ return 3.14*c.radius*c.radius*c.height}double surfac(const Cyclinder&c){ return 2*3.14*c.radius*c.height+2*3.14*c.radius*c.radius

//代码如下

#include <iostream>

using namespace std

class Cat{

friend int getTotalWeight()

private:

static int numOfCats

static int totalWeight

int weight

public:

Cat(int w){ weight=wnumOfCats++totalWeight+=w}

static int getNumOfCats(){

return numOfCats

}

}

class Dog{

friend int getTotalWeight()

private:

static int totalWeight

int weight

public:

Dog(int w){weight =wtotalWeight+=w}

}

int getTotalWeight(){

return Dog::totalWeight + Cat::totalWeight

}

int Cat::numOfCats = 0

int Cat::totalWeight = 0

int Dog::totalWeight = 0

int main(int argc, char *argv[]) {

Cat cat1(23)

Cat cat2(123)

Cat cat3(32)

cout<<"Total number of cats: "<<Cat::getNumOfCats()<<endl

Dog dog1(100)

Dog dog2(100)

cout<<"Total weight of all cats and dogs: "<<getTotalWeight()<<endl

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12266523.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存