Cocos2dx之C++基础(四)

函数重载
函数不以返回值来区分重载函数
函数不以参数名来区分重载函数
使用重载函数的时候不要引起二义性
结构函数也可以重载
函数重载又叫编译时多态

int square(int x)
{
    cout<<__FILE__<<__func__<<__LINE__<<endl;
    
    return x*x;
}

float square(float x)
{
    cout<<__FILE__<<__FUNCTION__<<__LINE__<<endl;
    
    return x*x;
}

double square(double x)
{
    cout<<__FILE__<<__func__<<__LINE__<<endl;
    
    return x*x;
}

多态:运行时多态
定义一个基类的指针,指向子类的变量

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;
    }

//    virtual int area() = 0;
//   纯 虚函数  = 0 告诉编译器 没有主题  因为实现多态 一般不需要实现父类中的虚函数
};


class Rectange : public Shape{
public:
    Rectange (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);
    }
};

// 使用
    Shape *shape;
    
    Rectange rec(10, 7);
    Triangle tri(20, 8);
    
    
    //  存储正方形的 地址
    // 调用的是 矩形的求面积公式
    shape = &rec;
    shape->area();
    
    
    // 调用的三角形的求面积方法
    shape = &tri;
    shape->area();

// 如果基类中没有用virtual修饰, 那么 调用的就是基类中的 area方法了
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.面向对象的程序设计思想是什么? 答:把数据结构和对数据结构进行操作的方法封装形成一个个的对象。 2.什么是类?...
    少帅yangjie阅读 5,052评论 0 14
  • const 引用 const 引用是指向 const 对象的引用:const int ival = 1024;co...
    rogerwu1228阅读 661评论 0 1
  • 重新系统学习下C++;但是还是少了好多知识点;socket;unix;stl;boost等; C++ 教程 | 菜...
    kakukeme阅读 20,046评论 0 50
  • struct与class的区别 C的struct与C++的class的区别:struct只是作为一种复杂数据类型定...
    geekzph阅读 1,615评论 0 4
  • 下面我们用系统自带的来新建.framework.然后再添加一个依赖库 AFNetworking xcode的菜单栏...
    NJ_墨阅读 767评论 0 0