C++中,如何在一个类中实现两种构造方式,而这两种的参数列表相同?

新手上路,请多包涵

比如 一种传入一个需要被处理的字符串作处理,另一种传入一个路径,读取文件后作处理。
有何合理的办法使这两种构造方式共存

阅读 2.4k
1 个回答

If the two signatures are the same, it is not possible. So, the first solution: add one more tag in parameter list, like

struct Foo
{
    struct Path {};
    struct NonPath {};
    foo(std::string, Path) { /* ... */ }
    foo(std::string, NonPath) { /* ... */ }
};
int main()
{
    // ...
    auto f1 = foo(s1, Foo::Path);
    auto f2 = foo(s2, Foo::NonPath);
    return 0;
}

Of course, you can also create two different Classes.

The two solutions above will be subtle if you have more constructors. Best practice is
Named Constructor Idiom:

struct Foo
{
private:
    std::string str;
    Foo(std::string s) : str(s) {}
public:
    static Foo path(std::string s) { /* ... */ return Foo(s); }
    static Foo non_path(std::string s) { /* ... */ return Foo(s); }
};
int main()
{
    // ...
    auto f1 = Foo::path(s1);
    auto f2 = Foo::non_path(s2);
    return 0;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题