![](/img/trans.png)
[英]Compile error: “no matching function for call to” when returning static_cast reference
[英]Static_cast no matching function for call
你能解释一下static_cast的工作吗?
为什么这段代码不起作用?
D another_d = static_cast<D>(br); // ERROR - no matching function for call to ‘D::D(B&)’
我的代码
#include <bits/stdc++.h>
using namespace std;
struct B {
int m = 0;
void hello() const {
std::cout << "Hello world, this is B!\n";
}
};
struct D : B {
void hello() const {
std::cout << "Hello world, this is D!\n";
}
};
int main(){
D d;
B br = d; // upcast via implicit conversion
br.hello(); // Hello world, this is B!
// D another_d = static_cast<D>(br); // ERROR - no matching function for call to ‘D::D(B&)’
D& another_d = static_cast<D&>(br); // OK
another_d.hello(); // Hello world, this is D!
}
B br = d; // upcast via implicit conversion
这是object 切片。 br
是B
的一个实例,只复制d
的B
部分。 (这意味着将d
向下转换为B&
编译器可以隐式执行,因为D
是从B
派生的。)
D another_d = static_cast<D>(br);
这是从B
的实例创建D
的实例的尝试。
虽然D
也是B
(由于继承),但事实并非如此。 因此,编译器无法隐式执行任何操作。
为了使其工作,必须定义构造函数D(B&)
。
为了说明这一点: D
可能具有无法从B
复制的其他成员变量,这是此类构造函数必须以任何方式处理的内容。
D& another_d = static_cast<D&>(br); // OK
这真的不行。 它可能(似乎)起作用,因为D
不包含其他成员变量。
br
是B
的一个实例(不是D
)。 “伪造”对D
的引用实际上是一个谎言,但明确地(在代码中)这样做会使编译器保持沉默。 但是,它仍然是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.