c++ - 如何引用结构存储的变量,该结构也是其他结构的一部分

标签 c++ struct

我正在尝试学习如何使用结构,但我遇到了(可能非常简单的)问题。如何引用属于 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/

相关文章:

c++ - 段错误常见原因的最终列表

c++ - 用 forkpty 和 execvp fork bash 后,bash 不响应 SIGINT

c++ - 结构元素的枚举 C++

c - 每个包含动态数组的结构数组

c - 我应该如何分配我的结构(指向结构数组的指针)?

c++ - 在 C/C++ 中使用二进制搜索在日志文件中搜索日期时间

c++ - 调试 Visual Studio 开发与 "Linux"开发的工作流方面?

c++ - 类对象数组的初始化 C++

C++数据结构代替数据库

c++ - 更新文件时如何防止结构成员值被覆盖 C++