如何传递std :: map作为默认构造函数参数 [英] How to pass std::map as a default constructor parameter

查看:1490
本文介绍了如何传递std :: map作为默认构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有能够弄清楚这一点。

I haven't been able to figure this out. It's easy to create two ctors but I wanted to learn if there's an easy way to do this.

如何通过 std :: map来创建两个ctors,但我想了解是否有一个简单的方法。 作为ctor的默认参数,例如

How can one pass a std::map as the default parameter to a ctor, e.g.

Foo::Foo( int arg1, int arg2, const std::map<std::string, std::string> = VAL)

've tried 0 null NULL as VAL ,没有工作,因为他们都是类型int,g ++抱怨。

I've tried 0, null, and NULL as VAL, none of the work because they are all of type int, g++ complains. What is the correct default to use here?

或者这是不是一个好主意?

Or is this kind of thing not a good idea?

推荐答案

VAL 的正确表达式是 std :: map< std :: string,std :: string& ()。我认为这看起来很长和丑陋,所以我可能添加一个公共typedef成员到类:

The correct expression for VAL is std::map<std::string, std::string>(). I think that looks long and ugly, so I'd probably add a public typedef member to the class:

class Foo {
public:
  typedef std::map<std::string, std::string> map_type;
  Foo( int arg1, int arg2, const map_type = map_type() );
  // ...
};

顺便问一下,你是不是要把最后一个构造函数的参数作为参考? const map_type& 可能优于 const map_type

And by the way, did you mean for the last constructor argument to be a reference? const map_type& is probably better than just const map_type.

这篇关于如何传递std :: map作为默认构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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