合并指针

Incorporating Pointers

本文关键字:指针 合并      更新时间:2023-10-16

我的代码似乎无法编译。我收到一个错误,上面写着:

无法将参数"1"的"Point**"转换为"Point*"

此错误发生在函数调用的两行上。我该怎么解决这个问题?

我最近刚刚将代码从引用传递改为严格的指针。

// This program computes the distance between two points
// and the slope of the line passing through these two points.
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
struct Point
{
    double x;
    double y;
};
double dist(Point *p1, Point *p2);
double slope(Point *p1, Point *p2);
int main()
{
    Point *p1, *p2;
    char flag = 'y';
    cout << fixed << setprecision(2);
    while(flag == 'y' || flag == 'Y')
    {
        cout << "First x value: "; cin >> p1->x;
        cout << "First y value: "; cin >> p1->y;
        cout << "Second x value: "; cin >> p2->x;
        cout << "Second y value: "; cin >> p2->y; cout << endl;
        cout << "The distance between points (" << p1->x << ", " << p1->y << ") and (";
        cout << p2->x << ", " << p2->y << ") is " << dist(&p1, &p2);
        if ((p2->x - p1->x) == 0)
        { cout << " but there is no slope." << endl; cout << "(Line is vertical)" << endl; }
        else
        { cout << " and the slope is " << slope(&p1, &p2) << "." << endl; }
        cout << endl;
        cout << "Do you want to continue with another set of points?: "; cin>> flag;
        cout << endl;
    }
    return 0;
}
double dist(Point *p1, Point *p2)
{
    return sqrt((pow((p2->x - p1->x), 2) + pow((p2->y - p1->y), 2)));
}
double slope(Point *p1, Point *p2)
{
    return (p2->y - p1->y) / (p2->x - p1->x);
}

老实说,您的代码在没有指针的情况下也很好。没有必要在这里介绍他们。

如果必须将指针作为赋值的一部分引入,并使用逐指针传递而不是逐引用传递,则需要进行一些更改。

  1. 将通过引用接收Point s的函数的签名更改为通过指针接收。例如,您将有"双坡度(点*p1,点*p2)"。

  2. 在这些函数的调用位置,显式传递参数的地址。例如,不调用slope(p1, p2),而是编写slope(&p1, &p2)

  3. 更新参数为Point*的函数体,使其使用->而不是.来访问其字段。

希望这能有所帮助!

您所要做的就是将元素作为指针接收,将它们作为引用发送,并使用运算符->:

double mydistance(Point *p1, Point *p2)
{
    return sqrt((pow((p2->x - p1->x), 2) + pow((p2->y - p1->y), 2)));
}

和通话

mydistance(&p1,&p2);

实际上,正如您在上一篇文章中所指出的,重命名distance函数或删除using namespace std,因为您正在调用std::distance()。这就是为什么我把这里叫做mydistance()。