C++(笔记)类实例

    xiaoxiao2021-03-25  73

    //定义一个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
    转载请注明原文地址: https://ju.6miu.com/read-16859.html

    最新回复(0)