测试代码:
Animals.h:
1 #pragma once 2 #include<string> 3 class Animals 4 { 5 protected: 6 std::string Food; 7 int Weight; 8 int Intake; 9 double Velocity; 10 public: 11 Animals(const std::string &fd="none",int w=0,int n=0,double v=0.0); 12 virtual void Speaking(); 13 void Swimming(); 14 void show(int)const; 15 virtual ~Animals(); 16 }; 17 18 class Fish :Animals 19 { 20 private: 21 std::string Colour; 22 public: 23 Fish(const std::string &cr = "none", const std::string &fd = "none", int w = 0, int n = 0, double v = 0.0); 24 Fish(const std::string &cr, Animals &tp); 25 void Appear()const; 26 void show()const; 27 void Speaking(); 28 29 };
Animals.cpp:
1 #include "stdafx.h" 2 #include "Animals.h" 3 #include<iostream> 4 5 Animals::Animals(const std::string &fd, int w, int n,double v):Food(fd),Weight(w),Intake(n), Velocity(v) 6 {} 7 8 void Animals::Speaking() 9 { 10 std::cout << "......" << std::endl; 11 } 12 13 void Animals::Swimming() 14 { 15 std::cout <<"++++++"<< Velocity << "m/s" <<"++++++"<< std::endl; 16 } 17 18 void Animals::show(int p) const 19 { 20 std::cout << "I want eatting "; 21 for (int i = 0; i < p; i++) 22 std::cout << Food<<"! "; 23 std::cout << std::endl; 24 } 25 26 Animals::~Animals() 27 { 28 } 29 30 31 Fish::Fish(const std::string & cr, const std::string & fd, int w, int n, double v) :Animals(fd,w,n,v) 32 { 33 Colour = cr; 34 } 35 36 Fish::Fish(const std::string & cr, Animals & tp):Animals(tp),Colour(cr) 37 {} 38 39 void Fish::Speaking() 40 { 41 std::cout << "Booo Booo!" << std::endl; 42 } 43 44 void Fish::Appear() const 45 { 46 std::cout << Colour << std::endl; 47 } 48 49 void Fish::show() const 50 { 51 std::cout << "Food: " << Food << std::endl; 52 std::cout << "Weight: " << Weight << std::endl; 53 std::cout << "Intake: " << Intake << std::endl; 54 std::cout << "Velocity: " << Velocity <<" m/s"<< std::endl; 55 std::cout << "Colour: " << Colour << std::endl; 56 }
ConsoleApplication.cpp:
1 #include "stdafx.h" 2 #include "Animals.h" 3 #include<iostream> 4 using namespace std; 5 int main() 6 { 7 Animals p0("shrimp", 20, 10, 1.0); 8 Fish b0("Red and White", "Coral", 10, 5, 0.5); 9 p0.show(3); 10 p0.Speaking(); 11 p0.Swimming(); 12 cout << endl ; 13 b0.show(); 14 cout << "Now I must speaking: "; 15 b0.Speaking(); 16 cout << endl ; 17 Fish b1("Blue", p0); 18 b1.show(); 19 cout << "Now I must speaking: "; 20 b1.Speaking(); 21 return 0; 22 }
运行结果: