C++ - упражнение #2
namespace Example2_ConstructorVsCast
{
namespace Intro1 // practice implicit cast with constructor
{
class A {};
class B { public: B(const A&){} }; // A->B conversion
void getB(const B&) {}
void trivial()
{
A a;
getB(a); // 'a' is implicitly casted to B with user-defined conversion (constructor)
}
}
namespace Intro2 // practive implicit cast to derived class and then implicit built-in cast to base type reference!
{
class C;
class A { public: operator C(); }; // A->C conversion
class B {};
class C : public B { };
void getB(const B&) {}
A::operator C() { return C(); }
void almostTrivial1()
{
A a;
getB(a); // do you know this works?
}
class A1 {};
class C1 : public B { C1(const A1 &) {} }; // A1->C1 conversion
void almostTrivial2()
{
#if 0
A1 a1;
getB(a1); // and this does not!
#endif
}
}
namespace Now // let's have both of them
{
class C;
class A {public: operator C(); }; // A->C conversion
class B {
public:
B() { }
B(const A&){} // A->B conversion
};
class C : public B { };
A::operator C() { return C(); }
void getB(const B&) {}
void almostTrivial()
{
A a;
getB(a); // which of two conversions is called?
}
}
}