//定义一个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
C++(笔记)类实例
最新推荐文章于 2023-05-04 21:30:00 发布