我正在尝试学习如何使用结构,但我遇到(可能非常简单)问题。我如何引用变量x,它由结构POINT存储,属于RECT结构?开始对我来说总是很难。
#include <iostream>
using namespace std;
struct Point {
int x, y;
};
struct Rect {
Point bottom_left, top_right;
};
void printPoint(const Point* p){
cout << "(" << p->x << "," << p->y << ")";
}
void printRect(const Rect* r){
cout << "["; printPoint(&r->top_right);
cout << ","; printPoint(&r->bottom_left);
cout << "]" << endl;
}
bool haveIntersection(const Rect* r1, const Rect* r2){
cout << &r1->bottom_left->x;
}
int main() {
Rect r1 = { {1,1}, {4,3} };
Rect r2 = { {2,0}, {3,4} };
Rect r3 = { {0,4}, {1,5} };
printRect(&r1);
haveIntersection(&r1, &r2);
}
答案 0 :(得分:4)
你的结构是
struct Point {
int x, y;
};
struct Rect {
Point bottom_left, top_right;
};
如果声明 Rect 对象:
Rect rectangle;
Rect* rectanglePtr = new Rect();
您可以通过以下方式访问x,y值:
rectangle.bottom_left.x;
rectanglePtr->bottom_left.x;
在您的情况下, haveIntersection 变为:
bool haveIntersection(const Rect* r1, const Rect* r2) {
/* Warning: you aren't using r2 var and return nothing */
cout << (r1->bottom_left).x;
}
答案 1 :(得分:2)
简直就是这样r1.bottom_left.x
请注意,r1.bottom_left
会返回Point&
。因此,您可以像使用其他任何Point