SRM Vision 暑期培训

by Leozheng @ SRMVision

§7 多态与运算符重载

#include <iostream>
class Complex {
private:
    int a, b;
public:
    Complex(int a = 0, int b = 0) {
        this->a = a; this->b = b;
    }
    void printCom() {
        std::cout << a << "+" << b << "i" << std::endl;
    }
    Complex operator+(const Complex& c2) {
        Complex tmp;
        tmp.a = a +c2.a;
        tmp.b = b +c2.b;
        return tmp;
    }
    Complex& operator=(const Complex &c2) {
        if (this == &c2) // 如果赋值给本身则直接返回
            return *this;
        // 因为在有些情况下可能会将原先的值清除后再赋值
        // 如果是自身赋给自身,那么先清除了数据显然就不能赋值了
        a = c2.a;
        b = c2.b;
        return *this;
    }
    //前置++
    Complex& operator++() {
        this->a++;
        this->b++;
        return *this;
    }
    // 后置++
    Complex operator++(int) {
        Complex tmp = *this;
        ++*this;
        return tmp;
    }
};
int main()
{
    Complex c1(1, 2), c2(3, 4);
    Complex c3 = c1 + c2;
    Complex c4 = c1; ++c1;
    c1.printCom(); 
    c2.printCom(); 
    c3.printCom(); 
    c4.printCom();
    return 0;
}
#include <iostream>
using namespace std;
class base {
public:
    virtual void vfunc() {
        cout << "基类虚函数" << endl;
    }
    virtual ~base() {
        cout << "~base" << endl;
    }
};
class derived : public base {
public:
    void vfunc() override {
        cout << "子类重载虚函数" << endl;
    }
    ~derived() override {
        cout << "~derived" << endl;
    }
};
int main(){
    base b;
    derived c;
    b.vfunc();
    c.vfunc();
    
    base* d = new derived();
    delete d; // ~derived -> ~base
}

第七讲 - 作业:

#include <iostream>
#include <cstring>
using namespace std;
class Animal{
public:
    Animal(double weight=0, double age=0) : w(weight), a(age){
        cout << "Constructing an Animal." << endl;
    }
    virtual	~Animal(){
        cout << "Destructing an Animal." << endl;
    }
    void Print(){
        cout << "[ANIMAL] ";			// 此处无换行
    }
    virtual void Show(){
        cout << "An Animal (" << w << "Kg, "<< a << " years old). " << endl;
    }
protected:
    double w, a;				// 体重、年龄
};

class Cat : public Animal{
public:
    Cat(char *pName="NoName", double weight=0, double age=0): Animal(weight,age){
        strncpy(name, pName, sizeof(name));
        name[sizeof(name)-1] = '\0';
        cout<<"Constructing a Cat, " <<name<< " created."<<endl;
    }~Cat(){
        cout<<"Destructing a Cat, " <<name<< " deleted."<<endl;
    }
    void Print(){
        cout << "[CAT] ";			// 此处无换行
    }
    void Show(){
        cout  << name << ", a cat (" << w << "Kg, "
        << a << " years old). Meow..." << endl;
    }
protected:
    char name[20];
};

int main()
{
    Animal *pa;
    Cat *pc;
    pa = new Cat("Tom", 1, 2);
    pc = new Cat("Frisky", 3, 4);
    pa->Print(); pa->Show();
    pc->Print(); pc->Show();
    delete pa;
    delete pc;
    return 0;
}

填空:

请写出程序输出内容

感 谢

@ SRMVision