2012-01-17 39 views
1

林在這段代碼接收error C2082: redefinition of formal parameter 'rval'試圖顯式調用基本副本構造函數:調用基地的拷貝構造函數時,我收到錯誤

#include <iostream> 
using namespace std; 


class Base 
{ 
public: 
    Base(const Base& rhs){ cout << "base copy ctor" << endl; } 
}; 

class Derived : public Base 
{ 
public: 
    Derived(const Derived& rval) { Base(rval) ; cout << "derived copy ctor" << endl; } 
     // error C2082: redefinition of formal parameter 'rval' 
}; 

int main() 
{ 
    Derived a; 
    Derived y = a; // invoke copy ctor 
    cin.ignore(); 
    return 0; 
} 

但是,如果像這樣做:

Derived(const Derived& rval) { Base::Base(rval) ; cout << "derived copy ctor" << endl; } 

然後沒問題。

爲什麼我問這個? 根據上StackOwerflow

答案我沒有使用運營商::訪問基本副本構造函數, 所以爲什麼我收到此錯誤?

BTW:我使用Visual Studio 2010中

我有一個問題:

我一定要調用基的舉動構造在派生類中的用戶定義的移動構造函數?

回答

2

要叫你需要把調用的成員名單initalization

class Derived : public Base 
{ 
public: 
    Derived(const Derived& rval) : Base(rval) 
    { 
     cout << "derived copy ctor" << endl; 
    } 
}; 
+0

OHHH!是啊:D我怎麼忘了那個笑,你能回答我的第二個問題嗎?非常感謝! – codekiddy 2012-01-17 00:18:29

+0

@codekiddy我不知道你是否必須明確調用基本ctor的*精確*規則,但作爲一個個人規則,我總是明確地調用基類ctor。 – JaredPar 2012-01-17 00:48:26

1

假設你指的是基類的構造「搬家」的構造是拷貝構造函數 - 是的。你將不得不調用Base的構造函數。否則,定義派生對象中的基礎對象是否不完整。您可以調用基類的複製構造函數或常規構造函數。