C++知识2

1.类函数的重载特性

类函数的重载特性就是我们可以在类里面定义同名的函数,但是参数不同的函数。

class student
{
public :
			char name[60];
			int age;
			void test();
			void test(int a);
private :
			int haha;
};

重载函数在调用的时候,会根据参数的类型,然后去匹配相应的函数进行调用。

2.构造函数和析构函数

析构函数:假如我们定义了析构函数,当对象被删除或者生命周期结束的时候,就会触发析构函数。
构造函数:假如我们定义了构造函数,当对象被创建的时候,就会触发构造函数。
我们要怎么定义构造函数和析构函数?
1.析构函数和构造函数的名字必须和类名一模一样。
2.析构函数要在前面加上一个~
3.构造函数可以重载,析构函数不可以。
4.带参数的构造函数写法,在对象名后加(),参数填在()里。

3.类的继承

类的继承允许我们在新的类里面继承父类的public还有protected部分,private是不能被继承。
当我们觉得这个类不好的时候,可以使用类的继承,添加我们需要的功能。
格式

class 儿子 :pubilic 爸爸{
	public : 
	/
	protected:
	

};

例子:
class mystudeng:public student
{
	public:
			int grade;
};

在子类里面去访问父类的成员,也是通过.和->来访问的。

4.虚函数和纯虚函数

虚函数:有实际定义,允许派生类对它进行覆盖式的替换,用virtual来修饰。
纯虚函数:没有实际定义的虚函数就是纯虚函数。
虚函数优点:可以预留接口,实现分工合作。

怎么定义一个虚函数?

虚函数例子

class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      virtual int area()
      {
         cout << "Parent class area :" <<endl;
         return 0;
      }
};

class Rectangle: public Shape{
   public:
      Rectangle( int a=0, int b=0):Shape(a, b) { }
      int area ()
      { 
         cout << "Rectangle class area :" <<endl;
         return (width * height); 
      }
};

class Triangle: public Shape{
   public:
      Triangle( int a=0, int b=0):Shape(a, b) { }
      int area ()
      { 
         cout << "Triangle class area :" <<endl;
         return (width * height / 2); 
      }
};
// 程序的主函数
int main( )
{
   Shape *shape;
   Rectangle rec(10,7);
   Triangle  tri(10,5);
 
   // 存储矩形的地址
   shape = &rec;
   // 调用矩形的求面积函数 area
   shape->area();
 
   // 存储三角形的地址
   shape = &tri;
   // 调用三角形的求面积函数 area
   shape->area();
   
   return 0;
}

纯虚函数例子

class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      // pure virtual function
      virtual int area() = 0;
};

= 0 告诉编译器,函数没有主体,上面的虚函数是纯虚函数。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白q_5793545

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值