美文网首页
Cocos2dx之C++基础(四)

Cocos2dx之C++基础(四)

作者: 易水寒208 | 来源:发表于2017-10-18 11:24 被阅读0次

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

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方法了

相关文章

网友评论

      本文标题:Cocos2dx之C++基础(四)

      本文链接:https://www.haomeiwen.com/subject/memsuxtx.html