C++,多态练习

一、定义基类Animals,以及多个派生类,基类中至少包含虚函数perform()

#include 

using namespace std;

class Aniamls
{
private:
    string cry;
public:
    Aniamls() {}
    Aniamls(string cry):cry(cry) {}
    virtual void perform() = 0;  //纯虚函数
};

class Cat:public Aniamls
{
private:
    string c_cry;
public:
    Cat() {}
    Cat(string c_cry,string cry):Aniamls(cry),c_cry(c_cry) {}
    void perform()
    {
        cout << "喵喵喵..." << endl;
    }
};

class Dog:public Aniamls
{
private:
    string d_cry;
public:
    Dog() {}
    Dog(string d_cry,string cry):Aniamls(cry),d_cry(d_cry) {}
    void perform()
    {
        cout << "汪汪汪..." << endl;
    }
};
int main()
{
    Cat c;
    Dog d;
    Aniamls *p;
    p = &c;
    p->perform();
    p = &d;
    p->perform();
    return 0;
}

二、用函数模型实现不同数据类型的交换功能 

#include 
#include 
using namespace std;

template 
void fun(T &a,T &b)
{
    T temp;
    temp = a;
    a = b;
    b = temp;
}

int main()
{
    int a = 10,b = 20;
    fun(a,b);
    cout << a << setw(5) << b << endl;

    double c = 1.2,d = 2.5;
    fun(c,d);
    cout << c << setw(5) << d << endl;
    return 0;
}

你可能感兴趣的:(C++,c++,开发语言)