我正在尝试学习如何使用结构,但我遇到了(可能非常简单的)问题。如何引用属于 RECT 结构的 POINT 结构存储的变量 x?开始对我来说总是困难的。
#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);
}
最佳答案
你的结构是
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;
}
关于c++ - 如何引用结构存储的变量,该结构也是其他结构的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20499661/