003 Figuring in C/C++
1. Type Casting
/* dynamic_cast: Can be used only with pointers and references to class; Base-to-derived conversions are not allowed unless the base class is polymorphic; Can cast null pointers even between pointers to unrelated classes; Can also cast pointers of any type to void pointers (void*); If the cast failure it returns a null pointer or an exception of type bad_cast will thrown if convert to an impossible reference type. Note:cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. */
/* static_cast
Pointers/Referrence both Base <-> Derive,
but no safety check during runtime & no type-safety checks;
Any other non-pointer conversion that could also be performed implicitly;
Any conversion between classes with explicit constructors or operator functions; */
/* reinterpret_cast Converts any pointer type to any other pointer type (same to reference); The operation result is a simple binary copy of the value from one pointer to the other; */
/* const_cast Manipulates the constness of an object, either to be set or to be removed. Only for pointer, reference, or a pointer-to-data-member type*/
2. Function with copy parameter & return
include <cstdio>
class B {
public:
B():d(0){ printf("Construct B()\n"); }
~B(){ printf("Destruct ~B()%d\n", d); }
B(int i){ d=i; printf("Construct B(i)%d\n", d); }
private:
int d;
};
B Play( B b ) {
return b;
}
int main()
{
Play( 11 );
B b1 = Play(5);
return 0;
}Out:
Construct B(i)11 Destruct ~B()11 Destruct ~B()11 Construct B(i)5 Destruct ~B()5 Destruct ~B()5函数返回若有左值,则赋值给左值,否则赋值给临时值。
版权声明:本文为博主原创文章,未经博主允许不得转载。

浙公网安备 33010602011771号