gpt4 book ai didi

c++ - 显式地将 const 对象传递给构造函数,该构造函数采用对多态类的 const 引用

转载 作者:搜寻专家 更新时间:2023-10-31 00:23:22 25 4
gpt4 key购买 nike

我的类遇到了问题,将 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

关于c++ - 显式地将 const 对象传递给构造函数,该构造函数采用对多态类的 const 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2191076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com