#include <iostream>
#include <string>
using namespace std;
// 基类
class Animal {
protected:
string name;
int age;
public:
// 构造函数
Animal(string n, int a) : name(n), age(a) {
cout << "Animal constructor called" << endl;
}
// 虚函数
virtual void makeSound() {
cout << "Some animal sound" << endl;
}
// 纯虚函数
virtual void move() = 0;
// 析构函数
virtual ~Animal() {
cout << "Animal destructor called" << endl;
}
};
// 派生类
class Dog : public Animal {
private:
string breed;
public:
// 构造函数
Dog(string n, int a, string b) : Animal(n, a), breed(b) {
cout << "Dog constructor called" << endl;
}
// 重写虚函数
void makeSound() override {
cout << name << " says: Woof!" << endl;
}
// 实现纯虚函数
void move() override {
cout << name << " is running" << endl;
}
// 析构函数
~Dog() {
cout << "Dog destructor called" << endl;
}
};
// 运算符重载示例
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 运算符重载
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
// 输出运算符重载
friend ostream& operator<<(ostream& out, const Complex& c) {
out << c.real << " + " << c.imag << "i";
return out;
}
};