繁体   English   中英

static_cast 没有匹配的 function 供调用

[英]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 切片 brB的一个实例,只复制dB部分。 (这意味着将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不包含其他成员变量。

brB的一个实例(不是D )。 “伪造”对D的引用实际上是一个谎言,但明确地(在代码中)这样做会使编译器保持沉默。 但是,它仍然是错误的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM