2014-12-29 87 views
-1

我想在這裏的例子中定義一個拷貝構造函數。但是,我發現如果必須使用複製構造函數,默認/隱式構造函數不會使編譯器很高興。爲什麼這樣?它背後有什麼理由嗎?爲什麼在C++中創建複製構造函數之前需要顯式構造函數?

class DemoCpyConstructor 
{ 

private: 

    int priv_var1; 
    int priv_var2; 

public: 

    void setDemoCpyConstructor(int b1, int b2) 
    { 
     std::cout<<"The Demo Cpy Constructor Invoked"<<std::endl; 
     priv_var1 = b1; 
     priv_var2 = b2; 

    } 

    void showDemoCpyConstructor() 
    { 
     std::cout<<"The priv_var1 = "<<priv_var1<<std::endl; 
     std::cout<<"The priv_var2 = "<<priv_var2<<std::endl; 
    } 

    DemoCpyConstructor(const DemoCpyConstructor &oldObj) 
    { 
     std::cout<<"Copy Constructor Invoked.."<<std::endl; 
     priv_var1 = oldObj.priv_var1; 
     std::cout<<"Tweaking the copy constructor"<<std::endl; 
     priv_var2 = 400; 
    } 


}; 


int main(int argc, char *argv[]) 
{ 
    DemoCpyConstructor oldObj; 
    oldObj.setDemoCpyConstructor(120,200); 
    oldObj.showDemoCpyConstructor(); 

    DemoCpyConstructor newObj = oldObj; 

    newObj.showDemoCpyConstructor(); 

    return 0; 
} 

這是個什麼錯誤,我得到 -

error: no matching function for call to ‘DemoCpyConstructor::DemoCpyConstructor()’ 
+0

這裏你需要一個:'DemoCpyConstructor oldObj;' –

回答

1

無論何時定義任何構造的(意味着轉換,副本),並要使用默認的,以及你必須明確地提供它。它的規則

相關問題