【c++】 类的继承 基类和子类

基类和子类

基类:可以派生出其他的类,也可以成为父类或超类

子类:从基类中派生出来的类

#include<iostream>
#include<string>
using namespace std;
 
class Animal//父类 
{
public:
	string mouth;
 
	void eat();
	void sleep();
	void drool();
	
};
 
class Pig:public Animal//子类 ,用':' 不要忘了public 
{
public:
	void climb();
};
 
class Turtle:public Animal
{
public:	
	void swim();
};
 
void Animal::eat()
{
	cout<<"正在进食中~"<<endl;
}
 
void Animal::sleep()
{
	cout<<"洗洗睡了~"<<endl;
}
 
void Animal::drool()
{
	cout<<"垂涎三尺而不得,可怖";
}
 
void Pig::climb()
{
	cout<<"猪,所以会爬树,即使它们不能"<<endl;
}
 
void Turtle::swim()
{
	cout<<"被水淹没,不知所措,可怜,可怜"<<endl;
}
 
int main()
{
	Pig pig;
	Turtle turtle;//类的初始化 
 
	pig.eat();
	turtle.eat();
	pig.climb();
	turtle.swim();
 
	return 0;
}

在这里插入图片描述

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中,子类基类之间的转换可以通过型转换实现。在进行子类基类之间的转换时,需要注意以下几点: 1. 子类对象可以直接转换为基类对象,因为子类对象中包含了基类对象的所有成员。 2. 基类对象不能直接转换为子类对象,因为基类对象中不包含子类对象的成员。如果需要将基类对象转换为子类对象,则需要使用强制型转换,但这种转换可能会导致编译错误或运行时错误。 3. 在进行子类基类之间的指针转换时,可以使用dynamic_cast操作符进行安全转换。dynamic_cast操作符可以检查转换是否合法,如果转换不合法,则会返回空指针。 示例代码如下: ```c++ class Base { public: virtual void foo() { cout << "Base::foo() called" << endl; } }; class Derived : public Base { public: void foo() override { cout << "Derived::foo() called" << endl; } }; int main() { // 子类对象可以直接转换为基类对象 Derived d; Base &b = d; // 基类对象不能直接转换为子类对象 Base b2; // 编译错误:invalid static_cast from type 'Base' to type 'Derived&' // Derived &d2 = static_cast<Derived &>(b2); // 使用dynamic_cast进行安全转换 Base *pb = new Derived(); Derived *pd = dynamic_cast<Derived *>(pb); if (pd) { pd->foo(); // Derived::foo() called } else { cout << "dynamic_cast failed" << endl; } delete pb; return 0; } ``` 在上面的示例代码中,定义了一个基类Base和一个子类Derived,其中子类继承基类。在main函数中,首先将子类对象d转换为基类对象b,然后尝试将基类对象b2转换为子类对象d2,但这个转换是不合法的,会导致编译错误。接着定义了一个基类指针pb,将其指向子类对象,并使用dynamic_cast将其转换为子类指针pd,如果转换成功,则调用子类的foo方法,否则输出转换失败的信息。最后记得释放动态分配的内存。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值