C++类初识——小试小刀

来源:互联网 发布:telnet服务器端口不通 编辑:程序博客网 时间:2024/04/30 08:07

之前学了java,现在学C++比较容易理解面向对象概念。今晚搭好环境(minGW+eclipse+CDT),就顺便写了个程序。话少说,代码贴下面了。

monkey.h
#ifndef MONKEY_H_#define MONKEY_H_#include<string>using namespace std;class Monkey{public:Monkey(string nameValue, unsigned int ageValue);/* * name the monkey */void setName(string nameValue) ;/* * get the name of monkey */string getName() ;/* * update the monkey's age */void setAge(unsigned int ageValue);/* * get monkey's age */unsigned int getAge();/* * print the basic information of a monkey, * this looks like the toString() Method in java somehow */void print();private:string name;unsigned int age;};#endif /* MONKEY_H_ */

monkey.cpp
#include<iostream>#include<string>#include "monkey.h"using namespace std;Monkey :: Monkey(string nameValue,unsigned int ageValue){name = nameValue;age = ageValue;}void Monkey :: setName(string nameValue) {name = nameValue;}string Monkey::getName(){return name;}void Monkey::setAge(unsigned int ageValue){age = ageValue;}unsigned int Monkey::getAge(){return age;}void Monkey::print(){cout << "Hello!\nMy name is " << this->getName() << endl;cout << "I'm " << this->getAge() << " now.\n";cout << "nice to meet you!\n";}


test.cpp

#include<iostream>#include<string>#include "monkey.h"using namespace std;int main(){string name;unsigned int age;Monkey monkeyOne("James",23);monkeyOne.print();cout << "Five years later...\n";age = monkeyOne.getAge()+5;monkeyOne.setAge(age);name = "Old " + monkeyOne.getName();monkeyOne.setName(name);monkeyOne.print();return 0;}


输出结果:
Hello!My name is JamesI'm 23 now.nice to meet you!Five years later...Hello!My name is Old JamesI'm 28 now.nice to meet you!




原创粉丝点击