实践如下:
class Person{ private: int age; char name[25]; int hight; public: Person(int age, int hight, char* name); int getAge(); char* getName(); int getHight(){ return hight; } };
#include "Person.h" Person::Person(int age, int hight, char* name1){ Person::age = age; Person::hight = hight; Person::name = name1; } int Person::getAge(){ return age; } char* Person::getName(){ return name; }
#include <iostream> #include "Person.h" using namespace std; int main(){ cout << "面向对象实践:" << endl; cout << "end." << endl; return 0; }
第二版:
class Person{ private: int age; char name[25]; int hight; public: // 静态常量不允许修改 const static int SVar = 100; const static int Default_Age = 30; const static int Default_Hight = 166; // static 作为默认参数 Person(int age = Default_Age, int hight = Default_Hight){ this->age = age; this->hight = hight; } Person(Person &p); Person(Person *p); ~Person(); Person(int age, int hight, char name[25]); int getAge(); char* getName(); int getHight(){ return this->hight;//(*this).hight; } };
#include <iostream> #include <string.h> #include "Person.h" Person::Person(int age, int hight, char name[25]){ Person::age = age; Person::hight = hight; strcpy(Person::name, name); } Person::Person(Person &p){ age = p.age; hight = p.hight; } Person::Person(Person *p){ age = p->age; hight = p->hight; } Person::~Person(){ //delete[] name; std::cout<<"...~\n"; } int Person::getAge(){ return age; } char* Person::getName(){ return name; }
#include <iostream> #include "Person.h" using namespace std; int main(){ cout << "面向对象实践1:" << endl; Person p(1,1); cout << "age:" << p.getAge()<< endl; cout << "hight:" << p.getHight() << endl; char name[25] = "1212121212q"; Person pp(22,22,name); Person *p1 = &pp; cout << "age1:" << p1->getAge()<< endl; cout << "hight1:" << p1->getHight() << endl; cout << "name1:" << p1->getName() << endl; Person p2(p); cout << "age2:" << p2.getAge()<< endl; cout << "hight2:" << p2.getHight() << endl; Person p3(p1); cout << "age3:" << p3.getAge()<< endl; cout << "hight3:" << p3.getHight() << endl; // Person p4(NULL,NULL); // cout << "age4:" << p4.getAge()<< endl; // cout << "hight4:" << p4.getHight() << endl; cout << "Person::SVar:" << Person::SVar << endl; cout << "end1." << endl; return 0; }