gpt4 book ai didi

c++ - 使数据成员随处可访问,但只读

转载 作者:太空宇宙 更新时间:2023-11-04 12:15:34 25 4
gpt4 key购买 nike

我刚刚开始自己​​的 Windows API 包装器,在重写结构以包含 C++ 功能时遇到了一个不熟悉的主题。

我要转这个:

typedef struct _RECT {
LONG left;
LONG top;
LONG right;
LONG bottom;
} RECT, *PRECT;

进入

#define RECT_POS 1
#define RECT_SIZE 2

typedef struct WrapperRect // RECT
{
WrapperRect(); // all 0
WrapperRect (const double, const double, const double, const double, bool = RECT_POS); // initalize with tl pos and either br pos or size

bool set (const double, const double, const double, const double, bool = RECT_POS); // set tl pos and either br pos or size
bool pos (const double, const double); // set tl pos
bool size (const double, const double); // set size

WrapperRect & operator= (const WrapperRect &); // assign another rect
bool operator== (const WrapperRect &); // check for equality (pos+size)
bool operator!= (const WrapperRect &); // check for inequality (pos+size)
bool operator> (const WrapperRect &); // check for tl pos greater
bool operator< (const WrapperRect &); // check for tl pos less
bool operator>= (const WrapperRect &); // check for tl pos greater equal
bool operator<= (const WrapperRect &); // check for tl pos less equal
WrapperRect & operator+ (const POINT &); // move down/right
WrapperRect & operator- (const POINT &); // move up/left
WrapperRect & operator+= (const POINT &); // move down/right
WrapperRect & operator-= (const POINT &); // move up/left

double l, left, x; // left
double r, right; // right
double t, top, y; // top
double b, bottom; // bottom

double w, width; // width
double h, height; // height
} Rect, rect; // allow more convenient names

我唯一的问题是如果用户说

Rect myRect;  
myRect.right = 50;

它将设置右侧,但不能更改右侧的别名或宽度。

我也不希望成员是私有(private)的,因为我想要

cout << myRect.x;

语法而不是烦人的

cout << myRect.getX();

语法。
有什么办法可以做到这一点,还是必须使用 get 函数?

编辑:
我写这篇文章的时候真的没想到,我添加了一些返回值 (>.>) 并将 operator+ 等中的 double 更改为一个点。在接受之前,我开始尝试各种可能性。

最佳答案

公开您的数据成员是非常糟糕的做法。在你的类中拥有完全相同信息的多个拷贝也是非常糟糕的做法。它既低效又容易出错。

您肯定需要使用访问函数。

也就是说,您不需要 getX(); - 只需 x() 就可以了。

如果您真的打算避免使用函数语法,我想这样的事情没问题:

struct Rect
{
private:
double l, r, t, b;

public:
const double &x, &y;

Rect() : x(r), y(t) {}

...etc.
};

然后您可以安全地使用 r.x,尽管您仍然在某种程度上公开了您的实现。

关于c++ - 使数据成员随处可访问,但只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7844454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com