【问题标题】:Explicitly passing a const object to an constructor which takes const reference to a polymorphic class将 const 对象显式传递给构造函数,该构造函数将 const 引用指向多态类
【发布时间】:2010-02-03 10:00:00
【问题描述】:

我的类遇到了问题,将一个 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 类的构造函数之间的区别。 谢谢!

【问题讨论】:

  • 您在第二类声明中切换了“Base”和“Derived”。那是错字吗?此外,即使您在没有优化的 Debug 配置文件中编译,“调试器跳过此行”注释是否也适用?
  • 您正在创建基类的对象并传递它们——您不会获得多态行为。您需要引用或指向基类的指针来获得所需的行为。投射不是解决方案。
  • 参数是const引用,所以有多态行为的引用。

标签: c++ constructor explicit


【解决方案1】:

问题是你不是在声明一个对象,而是一个函数:

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

【讨论】:

  • 该死,你是对的。非常感谢!虽然我前段时间遇到过同样的问题,但我现在没有想到。
【解决方案2】:

为了将来参考,这是一个被称为最令人头疼的解析的怪癖,关于这个昵称的由来,请参阅另一个StackOverflow thread

【讨论】:

    猜你喜欢
    • 2011-09-19
    • 1970-01-01
    • 2014-06-04
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多