1. 程式人生 > >C++(筆記)類例項

C++(筆記)類例項

//定義一個Person類,成員變數age(年齡),和name(姓名),成員函式getName(),getAge(),setAge(int newAge),完成該類測試

#include <iostream>
#include "Person.h"
using namespace std;

int main()
{
    Person p;
    p.getName();
    p.setAge(14);
    p.getAge();
return 0;
}

/*class Person  
{
public:
    void getAge();
    void getName();
    void setAge(int newAge);
    Person();
    virtual ~Person();
private:
    int age;
    char name;

};*/
/*Person::Person() { } Person::~Person() { } void Person::setAge(int newAge) { age=newAge; } void Person::getName() { name='x'; cout<<name<<endl; } void Person::getAge() { cout<<age<<endl; }*/ //x //14 //給該類新增複製建構函式(已包括建構函式無參和實參),並測試 #include <iostream>
using namespace std; class Person{ public: void setAge(int newAge); void getAge(); void getName(); Person(int a,char n){ age=a; name=n; } Person(Person &p); int geta(){return age;} char getn(){return name;} private
: int age; char name; }; Person::Person(Person &p) { age=p.age; name=p.name; cout<<"copy"<<endl; } void Person::setAge(int newAge) { age=newAge; } void Person::getAge() { cout<<age<<endl; } void Person::getName() { cout<<name<<endl; } int main() { Person p(14,'s'); Person b(p); cout<<b.geta()<<endl; cout<<b.getn()<<endl; return 0; } //copy //14 //s //利用容器類vector定義一個存放Person的可變成陣列,往陣列中新增3個Person物件,設定物件的age後輸出 #include <iostream> #include <vector> using namespace std; class Person{ public: void setAge(int newAge); void getAge(); void getName(); Person(int a,char n){ age=a; name=n; } Person(Person &p); int geta(){return age;} char getn(){return name;} private: int age; char name; }; Person::Person(Person &p) { age=p.age; name=p.name; cout<<"copy"<<endl; } void Person::setAge(int newAge) { age=newAge; } void Person::getAge() { cout<<age<<endl; } void Person::getName() { cout<<name<<endl; } int main() { int i=0; vector <int>h; Person p(14,'s'); Person b(p); h.resize(3); h[0]=b.geta(); Person t(15,'g'); Person r(t); h[1]=r.geta(); Person s(16,'q'); Person w(s); h[2]=w.geta(); for(i=0;i<3;i++) { cout<<h[i]<<endl; } return 0; } //copy //copy //copy //14 //15 //16 //用new生成Person物件 #include <iostream> using namespace std; class Person{ public: void setAge(int newAge); void getAge(); void getName(); Person(int a,char n){ age=a; name=n; } Person(); Person(Person &p); int geta(){return age;} char getn(){return name;} // private: int age; char name; }; Person::Person(Person &p) { age=p.age; name=p.name; cout<<"copy"<<endl; } void Person::setAge(int newAge) { age=newAge; } void Person::getAge() { cout<<age<<endl; } void Person::getName() { cout<<name<<endl; } int main() { Person *q=new Person(3,'s');//下面一行既可以加上,也可以不加,因為這一行賦初值 //q->age=3; cout<<q->geta()<<endl; //q->name='s'; cout<<q->getn()<<endl; delete []q; return 0; } //3 //s