开发者

a way to omit taking names for objects that are used only to construct a final object

Suppose we have following two classes:

class Temp{
 public:
  char a;
  char b;
};
class Final{
 private:
  int a;
  char b;
  char c;
 public:
  Final(Temp in):b(in.a),c(in.b){}
  //rest of implementation
};

suppose the only use of objects of Temp class is to construct objects of Final class, so I wonder if in current standard of 开发者_StackOverflowc++ , we can using a macro or somehow tell the compiler, since this object of Temp class which I'm defining is only used in one line of code and that is as argument of constructor of Final class; take a name for it yourself so I don't bother myself taking one name for each object Of Temp class?


Well, that isn't really the only place Temp is used, because you have to construct a Temp object when you call the constructor, right?

As for "taking up names," you can use a nested class:

class Final 
{
public:
    struct ConstructorParameter { char a, b; };

    Final(const ConstructorParameter& in) { ... };
};

Or, of course, you could just make a constructor with the two parameters:

class Final
{
public:
    Final(char a, char b) { ... };
};


If it's just two sub-objects, use std::pair<char,char>.

If your actual code has more of them, use a tuple (either std::tuple or std::tr1::tuple or boost::tuple.)


there's no such thing as I want in current c++ standard, but in upcoming c++0x standard, to initialize an object of the Final class, we can write:

Final obj({'a','b'}); 

So no naming for initializer object of the Temp class !!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜