Animal.h 头文件
#ifndef ANIMAL_H_
#define ANIMAL_H_
#include <string>
using std::string;
class Animal {
public:
Animal();
Animal(string);
virtual ~Animal();
void say();
string getName();
void setName(string);
private:
string name;
};
#endif
Animal.cpp 实现文件
#include "Animal.h"
#include <iostream>
using namespace std;
Animal::Animal() {}
Animal::~Animal() {}
Animal::Animal(string name){
this->name = name;
}
void Animal::say(){
cout << "my name is " + Animal::getName() << endl;
}
string Animal::getName(){
return this->name;
}
void Animal::setName(string name){
this->name = name;
}
Main.cpp 执行文件
#include "Animal.h"
int main(int argc, char **argv) {
Animal animal ;
animal.setName("animal");
animal.say();
/*使用构造函数*/
Animal animal2("animal2");
animal2.say();
}