无论如何要限定std :: pair的成员资格? [英] Anyway to qualify the members of a std::pair?

查看:93
本文介绍了无论如何要限定std :: pair的成员资格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以使std::pair的成员具有比firstsecond更有意义的含义?

例如:

is there any way to qualify the members of an std::pair with something more meaningful that just first and second ?

for example :

std::pair<int, int> value;
value.first = something;
value.second = somethingelse;



我想拥有



I''d like to have

std::pair<int, int > value;
value.myfirstvalue = something;
value.mysecondvalue = somethingelse;




我知道我可以定义一个简单的结构




I know I could just define a simple struct

struct
{ 
   int myfirstvalue;
   int mysecondvalue;
};



但是我必须让需要访问它的每个人都可以看到该结构,std :: pair已经对所有人可见.

谢谢.



but I''d have to make this struct visible to everyone who need to access it, std::pair is already visible to all.

Thanks.

推荐答案

有几种方法(有些没有意义),例如,您可以使用preprocessor macros,或者如果您担心的话,可以使用两种(当然,为了实现您必须从结对struct派生的方法).
There are several ways (some make poor sense), for instance you may use preprocessor macros or if you''re concerned about, two methods (of course, in order to implement the methods you''ve to derive from the pair struct).


您可以使用继承

Could you use inheritence

class MyPair : private std::pair<int,> 
{
   public:
     void SetMyFirstValue(int value) { first=value; }
     void SetMySecondValue(int value) { second=value; }
     int GetMyFirstValue() { return first; }
     int GetMySecondValue() { return second; }
     
}



然后以
的身份访问



Then access as

MyPair value;
value.SetMyFirstValue(something);
value.SetMysecondValue(somethingelse);


如果您有一个包含此对的复合对象,则可以添加对这两个元素的引用.引用不是对象,因此不会占用额外的空间.它们仅用作别名,而这显然是您想要的:
If you have a compound object containing this pair, you can add references to the two elements. References are not objects and as such don''t take additional space. They only work as an alias, and that is what you apparently want:
class MyClass {
   std::pair<int,int> mypair;
   int& myfirstvalue;
   int& mysecondvalue;
public:
   MyClass() : myfirstvalue(mypair.first), mysecondvalue(mypair.second) {}
};


请注意,您将需要在每个构造函数中初始化这些引用,因此可能有点尴尬.


Note that you''ll need to initialize these references in each constructor, so this can be kind of awkward.


这篇关于无论如何要限定std :: pair的成员资格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆