将 const 对象显式传递给构造函数,该构造函数采用对多态类的 const 引用
我的类遇到了问题,将 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 it 时,它才可以与第二个版本(问题的显式构造函数调用)正常工作就像:
Problem(*(Base*)&Derived);
我没有意识到隐式调用和显式调用 Problem 类的构造函数之间的区别。 谢谢你!
I got into a problem with my classes, passing a const object (polymorphic structure) to an explicit constructor which takes a const reference to the base class of that polymorphic structure.
Here is the sample (this is not from my code, it is for explanation here)
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&)
}
It seems that it is working fine with the second version (explicit constructor call for Problem) only if i explicitly cast the Derived object to its base class Base it like:
Problem(*(Base*)&Derived);
I do not realize the difference between calling impicitly and explicitly the constructor of the Problem class.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是你没有声明一个对象,而是一个函数:
使用:
这是 C++ 继承的 C 声明语法的一个怪癖。
更多示例:
The problem is you aren't declaring an object, but a function:
Use:
This is a quirk of C's declaration syntax inherited by C++.
More examples:
为了将来的参考,这是一个被称为最令人烦恼的解析的怪癖,请参阅另一个StackOverflow 线程 关于这个昵称的起源。
For future reference, this is a quirk known as the most vexing parse, see another StackOverflow thread as to the origin of this nickname.