c++学习笔记(虚函数多态实现)
//fish.h
class fish
{
public:
fish();
virtual ~fish();
virtual void water();
};
//fish.cpp
#include "pch.h"
#include "fish.h"
#include <iostream>
using namespace std;
fish::fish()
{
cout << "fish build" << endl;
}
fish::~fish()
{
cout << "fish free" << endl;
}
void fish::water()
{
cout << "Fish water. " << endl;
}
//whale.h
#include "fish.h"
class whale :
public fish
{
public:
whale();
~whale();
void water();
};
//whale.cpp
#include "pch.h"
#include "whale.h"
#include <iostream>
using namespace std;
whale::whale()
{
cout << "whale build" << endl;
}
whale::~whale()
{
cout << "whale free " << endl;
}
void whale::water()
{
cout << "whale water. " << endl;
}
//test.cpp #include "test.h" #include "pch.h" #include "fish.h" #include <iostream> using namespace std; void Fun(fish *f) { f->water(); cout << "test build" << endl; } //main #include "pch.h" #include <iostream> #include "test.h" #include "fish.h" #include "whale.h" #include "test.h" using namespace std; int main() { std::cout << "Hello World!\n"; /* fish *f = new fish; f->water(); fish g; g.water(); */ whale *j = new whale; j->water(); whale h; h.water(); whale k; fish &l = k; Fun(&l); // delete f; delete j; }
我就笑笑,笑他什么是非多端。
我就笑笑,笑他什么都看不穿。

浙公网安备 33010602011771号