我想问一下问题在哪里?
我收到了错误:'unary *'的无效类型参数
我是c ++编程的新手,我使用java风格。 指针和解引用对我来说是个大问题。
我的应用程序得到输入值并保存为点对象,此后我应该找到2行的交集。
我想要返回一个Point对象,在其中我将计算x和y值。
.h文件
class Point {
public:
double x_val, y_val;
Point(double, double);
double x();
double y();
double dist(Point other);
Point add(Point b);
Point sub(Point b);
void move(double a, double b);
};
class Triungle {
public:
Triungle(std::string);
void compute_length();
void lines_intersect(Point a, Point b, Point c, Point d, Point *intersection);
Point a, b, c;
};
.cpp文件
Point::Point(double x = 0.0, double y = 0.0) {
x_val = x;
y_val = y;
}
double Point::x() {
return x_val;
}
double Point::y() {
return y_val;
}
double Point::dist(Point other) {
double xd = this->x() - other.x();
double yd = this->y() - other.y();
return sqrt(xd * xd + yd * yd);
}
Point Point::add(Point b) {
return Point(x_val + b.x_val, y_val + b.y_val);
}
Point Point::sub(Point b) {
return Point(x_val - b.x_val, y_val - b.y_val);
}
void Point::move(double a, double b) {
x_val += a;
y_val += b;
}
void Triungle::lines_intersect(Point a, Point b, Point c, Point d, Point *intersection) {
double x, y;
double A1 = b.y_val - a.y_val;
double B1 = b.x_val - a.x_val;
double C1 = a.y_val - (A1 / B1) * a.x_val;
double A2 = d.y_val - c.y_val;
double B2 = d.x_val - c.x_val;
double C2 = c.y_val - (A2 / B2) * c.x_val;
double det = (A1 / B1) - (A2 / B2);
if (det == 0) {
// lines are paralel
} else {
x = (C2 - C1) / det;
y = (A1 * C2 - A2 * C1) / det;
}
*intersection->x_val = x; // here i got error
*intersection->y_val = y; // here i got error
}
Triungle::Triungle(std::string s) {
cout << "enter first point of " << s << " triangle: ";
cin >> a.x_val;
cin >> a.y_val;
if (!(cin)) {
cout << "input error." << endl;
exit(1);
}
cin.clear();
cout << "enter second point of " << s << " triangle: ";
cin >> b.x_val;
cin >> b.y_val;
if (!(cin)) {
cout << "input error." << endl;
exit(1);
}
cin.clear();
cout << "enter 3 point of " << s << " triangle: ";
cin >> c.x_val;
cin >> c.y_val;
if (!cin) {
cout << "input error." << endl;
exit(1);
}
cin.clear();
}
我以这种方式调用函数
int main(int argc, char** argv) {
Triungle a("first");
Triungle b("second");
Point p;
a.lines_intersect(a.a, a.b, a.c, a.a, &p);
}
答案 0 :(得分:1)
intersection->member
将取消引用指针intersection
。这与
(*intersection).member
你不需要取消引用它两次。
答案 1 :(得分:1)
您在代码中执行的操作
*intersection->x_val = x;
等同于
(*(intersection->x_val)) = x;
因为通过指针->
选择的运算符比解除引用运算符*
具有更高的precedence,后者的优先级高于赋值运算符=
。
首先,您选择double x_val
班的成员Point
。
其次,您尝试将一元解除引用运算符*
应用于结果。并且因为x_val是double,而不是指针,这是取消引用运算符所期望的,编译器报告错误。
因此,取消引用运算符在这里过多,并且足以执行以下操作
intersection->x_val = x;
答案 2 :(得分:0)
假设你得到的错误是两行的编译错误:
*intersection->x_val = x; // here i got error
*intersection->y_val = y; // here i got error
问题是您要取消引用指针,然后在其上使用derefencing运算符->
。
相反,你应该这样做:
intersection->x_val = x;
intersection->y_val = y; // leave it as a pointer
或
*intersection.x_val = x;
*intersection.y_val = y; // use it as an object