代码之家  ›  专栏  ›  技术社区  ›  marolafm

对基构造函数的条件调用

  •  7
  • marolafm  · 技术社区  · 7 年前

    class Base {
    public:
       Base(std::string filname){...}
       Base(int a, int b) {...}
    };
    

    class Derived : public Base {
    public:
        Derived() {
            if( /* exists("myFile") */ )
                this->Base("myFile");
            else
                this->Base(1,2);
        }
    }
    

    可以这样做吗?或者因为基类在派生类之前初始化,所以调用基构造函数的唯一方法是在初始值设定项列表中?

    2 回复  |  直到 7 年前
        1
  •  7
  •   Daniel H    7 年前

    class Derived : public Base {
    public:
        Derived()
            : Base{ exists("myFile") ? Base{"myFile"} : Base{1, 2} } {
        }
    }
    

    exists("myFile") true ,它将构建一个临时的 Base false 它将构建一个临时的 使用第二个构造函数。不管怎样,它都将构建

        2
  •  1
  •   Maxim Egorushkin    7 年前

    class Base {
    public:
        Base(std::string filname);
        Base(int a, int b);
    };
    
    class Derived : public Base {
        Derived(std::string filname) : Base(filname) {}
        Derived(int a, int b) : Base(a, b) {}
    public:
        static Derived create() {
            if( /* exists("myFile") */ )
                return Derived("myFile");
            else
                return Derived(1,2);
        }
    };
    
    int main(){
        auto d = Derived::create();
    }
    

    Base 可作为成员持有( std::unique_ptr std::aligned_storage