C++代码为 Point 类添加一个友元函数 Point add ( Point p , Point q ),用于2个 Point 对象的相加运算。
时间: 2023-08-02 13:27:45 浏览: 56
以下是 C++ 代码实现:
```cpp
#include <iostream>
using namespace std;
class Point {
private:
double x, y;
public:
Point(double x = 0, double y = 0) : x(x), y(y) {}
void print() {
cout << "(" << x << ", " << y << ")" << endl;
}
friend Point add(Point p, Point q);
};
Point add(Point p, Point q) {
return Point(p.x + q.x, p.y + q.y);
}
int main() {
Point p1(1, 2), p2(3, 4);
Point p3 = add(p1, p2);
p3.print();
return 0;
}
```
在上面的代码中,我们定义了一个 Point 类,其中包含了 x 和 y 两个私有变量和一个打印函数。我们还定义了一个友元函数 add,用于计算两个 Point 对象的相加结果。该函数在类的外部定义,但是在函数前面加上了 friend 关键字,使其成为 Point 类的友元函数,可以访问 Point 类的私有成员变量。在 main 函数中,我们创建了两个 Point 对象,并使用 add 函数计算它们的和,最后输出结果。
相关问题
c++定义一个点类point
回答: 在C++中,可以定义一个点类Point,可以参考以下代码:
```cpp
class Point {
private:
int x;
int y;
public:
Point(int xCoord, int yCoord) {
x = xCoord;
y = yCoord;
}
int getX() {
return x;
}
int getY() {
return y;
}
void setX(int newX) {
x = newX;
}
void setY(int newY) {
y = newY;
}
};
```
在这个点类中,我们定义了私有的x和y坐标,并提供了公有的方法来获取和设置这些坐标。你可以根据自己的需求添加其他方法或成员变量。
#### 引用[.reference_title]
- *1* *2* [C++ 之点类point 输入10个点,求出10个点的距离](https://blog.csdn.net/xiao_jj_jj/article/details/83182536)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [C++1.作业定义学生类Student:...设计一个点类Point,分别用成员函数、友元函数、普通函数求两点之间的距离。](https://blog.csdn.net/m0_51748914/article/details/120581389)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
C++源代码编写一个程序,设计一个点类Point,求两个点之间的距离。要求分别用友元函数和成员函数来实现。
#include<iostream>
#include<cmath>
using namespace std;
class Point{
private:
double x,y;
public:
Point(double a=0,double b=0){x=a;y=b;}
friend double distance(Point a,Point b);
double distance(Point &p){return sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));}
};
double distance(Point a,Point b){
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
int main(){
Point p1(1,1),p2(4,5);
cout<<"使用友元函数求解两点之间的距离:"<<distance(p1,p2)<<endl;
cout<<"使用成员函数求解两点之间的距离:"<<p1.distance(p2)<<endl;
return 0;
}