2

クラスで問題が発生し、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 に明示的にキャストした場合にのみ、2 番目のバージョン (Problem の明示的なコンストラクター呼び出し) で正常に動作しているようです。

Problem(*(Base*)&Derived);

Problem クラスのコンストラクターを暗黙的に呼び出す場合と明示的に呼び出す場合の違いがわかりません。ありがとうございました!

4

2 に答える 2

6

問題は、オブジェクトではなく関数を宣言していることです。

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
于 2010-02-03T10:09:42.210 に答える
0

今後の参考のために、これは最も厄介な parseとして知られる癖です。このニックネームの由来については、別のStackOverflow スレッドを参照してください。

于 2010-02-03T14:41:24.477 に答える