在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

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

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

回答
編輯回答
挽歌

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