鍍金池/ 問(wèn)答/C++  網(wǎng)絡(luò)安全/ C++中,如何在一個(gè)類中實(shí)現(xiàn)兩種構(gòu)造方式,而這兩種的參數(shù)列表相同?

C++中,如何在一個(gè)類中實(shí)現(xiàn)兩種構(gòu)造方式,而這兩種的參數(shù)列表相同?

比如 一種傳入一個(gè)需要被處理的字符串作處理,另一種傳入一個(gè)路徑,讀取文件后作處理。
有何合理的辦法使這兩種構(gòu)造方式共存

回答
編輯回答
挽歌

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;
}
2018年9月16日 09:13