引用可能是指向结构的成员C++
Reference could be pointing struct's members in C++
我们是否可以创建一个包含一些值和指向同一结构中的值的引用的结构?我的想法是用假名。所以我可以用不同的方式调用struct成员!
struct Size4
{
float x, y;
float z, w;
float &minX, &maxX, &minY, &maxY;
Size4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w),
minX(x), maxY(y), minY(z), maxY(w)
{
}
};
谢谢大家。
NB:我用指针做了,但是现在当我试图调用Size4.minX()
时,我得到的是地址,而不是值。
struct Size4
{
float x, y;
float z, w;
float *minX, *maxX, *minY, *maxY;
Size4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w),
minX(&x), maxX(&y), minY(&y), maxY(&w)
{
}
};
"我想让它透明。Size4大小(5 5 5 5);size.minX;和size.x;返回相同的值…"
你可以这样做。但是,我建议您使用class
。
using namespace std;
struct Size4
{
float x, y;
float z, w;
float *minX, *maxX, *minY, *maxY;
Size4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w),
minX(&x), maxX(&y), minY(&y), maxY(&w)
{
}
};
int main() {
Size4 s(1,2,3,4);
std::cout << *(s.minX) << std::endl;
return 0;
}
或者你可以在你的struct
float getX() {
return *minX;
}
,并像这样访问它:
std::cout << s.getX() << std::endl;
然而,class
将提供更好的封闭。私有数据成员和get-er函数访问minX
.
使用class
很简单,像这样:
#include <iostream>
using namespace std;
class Size4
{
private:
// these are the private data members of the class
float x, y;
float z, w;
float *minX, *maxX, *minY, *maxY;
public:
// these are the public methods of the class
Size4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w),
minX(&x), maxX(&y), minY(&y), maxY(&w)
{
}
float getX() {
return *minX;
}
};
int main() {
Size4 s(1,2,3,4);
std::cout << s.getX() << std::endl;
// std::cout << *(s.minX) << std::endl; <-- error: ‘float* Size4::minX’ is private
return 0;
}
使用解引用运算符取值:*(size4.minx)
一个小例子:
Size4 sz(11, 2, 3, 4);
printf("%f, %f, %f, %f", *sz.minX, *sz.maxX, *sz.minY, *sz.maxY);
相关文章:
- 具有结构成员char数组的sscanf
- 仅使用结构名称访问结构成员
- 使用 structType*& 赋给结构成员
- 使用结构成员指针在C++中填充结构
- 聚合初始化,将成员指针设置为同一结构成员
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 是否可以将结构数组别名为结构成员数组?
- 结构成员在访问时被清除
- 如何指示结构成员没有锯齿?
- 为什么继承的结构成员在联合中无法访问?
- 尝试在 qml 中访问结构成员的 QList
- C++/CLI -- 访问结构成员
- 调用在类中声明的结构成员
- 对结构成员的临时绑定引用
- 无法使用 strcpy 将字符串复制到静态结构成员
- 为什么类成员数据必须是静态的才能被模板化类的模板化结构成员访问
- 填充模板化结构类型的结构成员
- C/C++intellisense 0.26.1不显示结构成员列表
- 在源文件中创建具有结构成员的结构
- 如何访问结构成员作为指针