c ++ fifth experiment

part 1

Two questions:

1, members of the base class of the same name appears in a derived class, the object name. Manner member name, i.e., the code base2.display (), is a member of the derived class access member

2, a derived class object pointer to access through a base class, Not ex1_1.cpp in virtual, the result is all calls the base class member function in the base class member function ex1_2.cpp there is virtual, the results derived classes of base class turn calls. Virtual function is a dynamic binding basis, essentially covering not overloaded.

 

Part 3

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 class MachinePets
 6 {
 7 public:
 8     MachinePets(const string s);
 9     MachinePets();
10     string getNickname();
11     virtual string talk() = 0;
12     virtual ~MachinePets();
13 private:
14     string nickname;
15 };
16 
17 void play(MachinePets *p)
18 {
19     cout << p->getNickname();
20     cout << p->talk() << endl;
21 }
22 
23 MachinePets::MachinePets(const string s) :nickname(s)
24 {
25 }
26 
27 
28 string MachinePets::getNickname()
29 {
30     return nickname;
31 }
32 
33 MachinePets::~MachinePets()
34 {
35 }
36 
37 
38 
39 
40 
41 
42 class PetCats :public MachinePets
43 {
44 public:
45     PetCats(const string s);
46     ~PetCats();
47     string talk();
48 };
49 
50 PetCats::PetCats(const string s) :MachinePets(s)
51 {
52 }
53 string PetCats::talk()
54 {
55     return " says miao wu~";
56 }
57 PetCats::~PetCats()
58 {
59 }
60 
61 
62 
63 
64 
65 class PetDogs :public MachinePets
66 {
67 public:
68     PetDogs(const string s);
69     ~PetDogs();
70     string talk();
71 };
72 
73 PetDogs::PetDogs(const string s) :MachinePets(s)
74 {
75 }
76 string PetDogs::talk()
77 {
78     return " says wang wang~";
79 }
80 PetDogs::~PetDogs()
81 {
82 }
83 
84 
85 
86 int main() {
87     PetCats cat("miku");
88     PetDogs dog("da huang");
89     play(&cat);
90     play(&dog);
91     return 0;
92 }
pet

The following error appears on the practice courses:

Item file line severity codes prohibit the display state
error LNK2005 "void __cdecl play (class MachinePets *)" (play @@ YAXPAVMachinePets @@@ Z?) Has been defined in MachinePets.obj in part3 C: \ Users \ lenovo \ Desktop \ part3 \ part3 \ PetDogs.obj 1 

Reason is that it online: c ++, header files can not be separated cpp file write function template (template <class T> and the like). This means that you place the template containing the header file definition must be implemented in the header file, where useless defined templates can be placed cpp implemented. (There is also a telling me to re-install)

Not quite understand, always felt should open a new write together, write separately on this issue did not appear before several times. The results compiled successfully.

 

Guess you like

Origin www.cnblogs.com/lovecpp/p/10937037.html