c++ - Assignment of base class object to derived class object -
why error: no match ‘operator=’ in ‘y = x’
in following code?
cant a-component of b not assigned a-object = a-object
?
struct {int i;}; struct b : public {int j;}; int main() { x; b y; x.i = 9; y.j = 5; y = x; // error: no match ‘operator=’ in ‘y = x’ // expected: y.i = 9 return 0; }
you not explicitly defining assignment operators, compiler generate own default operators each struct. compiler's default assignment operator in b
takes b
input , assign both members. , assignment operators not automatically inherited when using inheritance. why cannot pass a
b
- there no assignment operator in b
takes a
input. if want allow that, need tell compiler much, eg:
struct { int i; a& operator=(const &rhs) { = rhs.i; return *this; } }; struct b : public { int j; using a::operator=; b& operator=(const b &rhs) { *this = static_cast<const a&>(rhs); j = rhs.j; return *this; } }; int main() { x; b y; b z; ... y = x; // ok y = z; // ok ... return 0; }
Comments
Post a Comment