انواع کست کردن در سی پلاس پلاس
کست کردن, به انگلیسی casting به معنی تبدیل type شیء به یک type دیگر است.
- reinterpret_cast
- dynamic_cast
- const_cast
- ...
static_cast
برای تبدیل type اعداد در زمان compile کاربرد دارد؛ به عنوان مثال, تبدیل int به float یا double.
int x = 10;
double y = static_cast<double>(x);
این شکل از casting معادل casting رایج در C است.
int x = 10;
double y = (double)x;
منظور از compile-time بودن به این معنی است که کد کامپایل شده متغیری از نوع cast خواهد بود.
Polymorphism
پلیمرفیزم, به انگلیسی polymorphism در شیء گرایی به معنی داشتن عملکرد متفاوت اشیاء, با interface کلاس یکسان است.
کست رو به بالا یا upcasting
آپ کستینگ, به انگلیسی upcasting یعنی تبدیل شیء کلاش مشتق شده یا derived-class به base-class یا کلاس والد یا پایه.
// Base-class
class Animal {
public:
void eat() { cout << "Animal is eating"; }
};
// Derived-class
class Dog : public Animal {
public:
void bark() { cout << "Dog is barking"; }
};
int main() {
// Make an object of the derived-class
Dog myDog;
// Upcast to get an object of the base-class
Animal * myAnimal = &myDog;
// Works fine because it's an object of the base-class
myAnimal->eat(); // کار میکنه
// Doesn't work because it's been upcasted, and is an object of the parent class not the child
// myAnimal->bark();
return 0;
}
کست رو به پایین یا downcasting
کست رو به پایین, به انگلیسی downcasting یعنی تبدیل شیء کلاس پایه یا والد, به انگلیسی base-class به derived-class یا شیء کلاس فرزند یا مشتق.
class Parent {
public:
void sleep() {}
};
class Child: public Parent {
public:
void gotoSchool(){}
};
int main( )
{
Parent parent;
Child child;
// upcast - implicit type cast allowed
Parent *pParent = &child;
// downcast - explicit type case required
Child *pChild = (Child *) &parent;
pParent -> sleep();
pChild -> gotoSchool();
return 0;
}
comments