Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

c++ - Static_cast no matching function for call

Could you please explain work of static_cast?

Why this code doesn't work?

D another_d = static_cast<D>(br); // ERROR - no matching function for call to ‘D::D(B&)’

My code

#include <bits/stdc++.h>

using namespace std;

struct B {
    int m = 0;
    void hello() const {
        std::cout << "Hello world, this is B!
";
    }
};

struct D : B {
    void hello() const {
        std::cout << "Hello world, this is D!
";
    }
};

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!
}
question from:https://stackoverflow.com/questions/65871998/static-cast-no-matching-function-for-call

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
B br = d; // upcast via implicit conversion

This is object slicing. br is an instance of B and copies only the B part of d. (This implies down-casting of d to B& which the compiler can do implicitly because D is derived from B.)

D another_d = static_cast<D>(br);

This is the attempt to create an instance of D from an instance of B.
While D is also a B (due to inheritance) the opposite is not true. So, there is nothing the compiler can do implicitly.

To make this working, a constructor D(B&) has to be defined.

To illustrate this: D might have additional member variables which cannot copied from B, and this is what such constructor had to handle in any way.

D& another_d = static_cast<D&>(br); // OK

This is not really OK. It might (seem to) work as D doesn't contain additional member variables.

br is an instance of B (not of D). "Faking" a reference to D is actually a lie but doing this explicitly (in code) makes the compiler silent. However, it's still wrong.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...