簡體   English   中英

顯式地將const對象傳遞給使用const引用多態類的構造函數

[英]Explicitly passing a const object to an constructor which takes const reference to a polymorphic class

我遇到了類問題,將const對象(多態結構)傳遞給顯式構造函數,該構造函數采用const引用該多態結構的基類。 這是示例(這不是來自我的代碼,在這里用於解釋)

class Base 
{
...
}

class Derived:public Base
{
...
}

class Problem 
{
    Problem(const Base&);
...
}

void myFunction(const Problem& problem) 
{
    ...
}

int main() 
{
    //explicit constructor with non const object
    Derived d;
    Problem no1(d); //this is working fine 
    myFunction(no1);

    //implicit constructor with const object
    Problem no2=Derived(); //this is working fine, debugged and everything called fine
    myFunction(no2);   //is working fine

    //explicit constructor with const object NOT WORKING
    Problem no3(Derived());  //debugger jumps over this line (no compiler error here)
    myFunction(no3);   //this line is NOT COMPILING at all it says that:
    //no matching function for call to myFunction(Problem (&)(Derived))
    //note: candidates are: void MyFunction(const Problem&)
}

似乎只有在我將Derived對象顯式轉換為它的基類Base時,它才能與第二個版本(對問題的顯式構造函數調用)一起正常工作:

Problem(*(Base*)&Derived);

我沒有意識到隱式調用和顯式調用Problem類的構造函數之間的區別。 謝謝!

問題是您不是在聲明一個對象,而是一個函數:

Problem no3(Derived());
// equivalent to:
Problem no3(Derived); // with parameter name omitted

采用:

Problem no3((Derived()));
// extra parens prevent function-declaration interpretation
// which is otherwise required by the standard (so that the code isn't ambiguous)

這是C ++繼承的C聲明語法的怪癖。

更多示例:

void f(int(a)); /* same as: */ void f(int a);

void g() {
  void function(int);    // declare function
  void function(int());  // we can declare it again
  void function(int=42); // add default value
  function();            // calls ::function(42) ('function' in the global scope)
}
// 'function' not available here (not declared)

void function(int) {} // definition for declarations inside g above

供以后參考,這是一個被稱為最令人討厭的語法分析的怪癖,有關此昵稱的起源,請參見另一個StackOverflow線程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM