2014-05-18 53 views
2

我们能否创建一个包含一些值的结构和指向同一结构中的值的引用?我的想法是制作别名。所以我可以用不同的方式调用struct成员!引用可能指向struct的成员在C++中

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) 
    { 
    } 

}; 

谢谢大家。

注意:我是用指针做的,但是现在当我试图拨打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) 
    { 
    } 
}; 
+1

当然可以。然而,参考文献不能重新分配,所以我没有看到太多的用处。你想完成什么,并且你了解了[指向成员](http://stackoverflow.com/questions/670734/c-pointer-to-class-data-member)? – StoryTeller

+0

感谢指向成员链接的指针,但通过添加解析地址操作符(*)可以访问此解决方案。 – dsimonet

+0

我想让它透明。 尺寸4尺寸(5,5,5,5); size.minX;和size.x;返回相同的值... – dsimonet

回答

1

“我想使它透明尺寸4尺寸(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; 
} 
+0

也许这种方法对我来说是最好的方式......谢谢 – dsimonet

+0

你的例子没有说明如何使用一个类,它只是在结构中重新使用OP自己的指针用例。 – StoryTeller

+0

我在附近提出了一个问题,前几天:http://stackoverflow.com/questions/23678523/rename-member-by-inherit-class-in-c 我不能在结构中做同样的事情? – dsimonet

0

使用对其操作把你的价值:*(size4.minx)

一个小例子:

Size4 sz(11, 2, 3, 4); 
printf("%f, %f, %f, %f", *sz.minX, *sz.maxX, *sz.minY, *sz.maxY); 
+0

感谢您的回答,但解引用正是我所要避免的。我试图让它透明。如果我不能,我会通过get和set方法创建类。 – dsimonet

+0

对于我来说,带有二传手和得分手的上课会更好。 – Netherwire