合并指针
Incorporating Pointers
我的代码似乎无法编译。我收到一个错误,上面写着:
无法将参数"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);
}
老实说,您的代码在没有指针的情况下也很好。没有必要在这里介绍他们。
如果必须将指针作为赋值的一部分引入,并使用逐指针传递而不是逐引用传递,则需要进行一些更改。
-
将通过引用接收
Point
s的函数的签名更改为通过指针接收。例如,您将有"双坡度(点*p1,点*p2)"。 -
在这些函数的调用位置,显式传递参数的地址。例如,不调用
slope(p1, p2)
,而是编写slope(&p1, &p2)
。 -
更新参数为
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()。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 运行几次后合并段错误C++(指针算术)
- 如何使用指针合并 2 个数组
- C++:在合并对象时管理指针
- C++使用指针合并文本
- 合并指针
- 在c++中构建/合并字符数组指针
- 我的(基于指针的)合并排序有什么问题?
- 将void指针的两个矢量(void*)合并到生成的新矢量中