【问题标题】:Incorporating Pointers [closed]合并指针[关闭]
【发布时间】:2014-11-03 13:53:23
【问题描述】:

我的代码似乎无法编译。我收到一条错误消息:

无法将参数“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);
}

【问题讨论】:

  • “将指针合并到程序中”是什么意思?看起来你在这里不需要指针。
  • 是的。我的程序编译完美,但为了满足项目要求,我需要将其转换为指针。我需要严格使用指针,而不是使用指针通过引用传递。 @templatetypedef
  • 至少你可以上传更正后的代码。
  • 您的 dist 和 slope 函数可以采用 const 指针或引用。

标签: c++ pointers


【解决方案1】:

老实说,您的代码没有指针就可以了。这里没有必要介绍它们。

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

  1. 将通过引用接收Points 的函数的签名更改为通过指针接收它们。例如,你会有`双斜率(Point* p1, Point* p2)。

  2. 在这些函数的调用点,显式传入参数的地址。例如,不要调用slope(p1, p2),而是写slope(&amp;p1, &amp;p2)

  3. 更新参数为Point*s 的函数体以使用-&gt; 而不是. 来访问它们的字段。

希望这会有所帮助!

【讨论】:

    【解决方案2】:

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

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

    并调用

    mydistance(&p1,&p2);
    

    实际上,正如您在上一篇文章中指出的那样,重命名距离函数或删除 using namespace std,因为您正在调用 std::distance()。这就是我在这里调用 mydistance() 的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 2010-09-28
      • 1970-01-01
      • 2017-09-01
      相关资源
      最近更新 更多