通过析构函数给变量赋值
自己不写,编译器自动写成person(){ }
这时会等main中全部代码执行完才释放
//
// Created by archi on 2022/11/23.
//
#include "iostream"
using namespace std;
class Clock
{
public:
Clock(int hour,int minute,int second);//构造函数
Clock();//默认构造函数
void settime(int shour,int sminute,int ssecond);
void showtime(void);
private:
int hour,minute,second;
};
void Clock::settime(int shour, int sminute, int ssecond) {
hour=shour;
minute=sminute;
second=ssecond;
}
void Clock::showtime(){
cout<<"now the time is:"<<endl<<hour<<endl<<minute<<endl<<second;
}
Clock::Clock(int nhour, int nminute, int nsecond) {//外联函数声明
hour = nhour;
minute = nminute;
second = nsecond;
}
Clock::Clock():hour(1),minute(2),second(3){}//使用默认构造函数赋值
int main(void)
{
Clock b;//不赋值
b.showtime();
cout<<endl;
Clock a(1,2,3);//使用构造函数赋值
a.showtime();
cout<<endl;
a.settime(22,25,36);
a.showtime();
cout<<endl;
a.settime(22,46,20);
a.showtime();
}
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<cstring>
using namespace std;
class student {
private:
char ID[20];//学号
char Name[20];//姓名
char Number[20];//联系方式
public:
student(){};//默认构造函数,可以自定构造函数给变量赋值
~student() {};//析构函数,用于清理工作
void getid(char id[]);
void showid(void) { cout << "ID:" << ID; };
void getname(char name[]) { strcpy(Name, name); }//内联函数声明
void showname(void) { cout<<Name; }//内联函数声明
void getnumber(char a[]);
void shownumber(void) { cout << "Number:" << Number; }
};
void student::getid(char id[]) {//外联函数声明
strcpy(ID,id);
}
void student::getnumber(char a[]) { strcpy(Number, a); }
int main(void) {
student stu1;//创建静态student 对象stu1
student* p = new student [2];//动态创建两个student对象
if (p == NULL)
{
return 1;//判断是否分配成功,不成功返回1
}
int i = 0;
student* q[2] = { &p[0],&p[1] };//创建指针数组,包含两个结构体指针,同下
//student* q1 = &p[0];//结构体指针q1
//student* q2 = &p[1];//结构体指针q2
for (i = 0; i < 2; i++) {//输入姓名和学号
cout << "输入" << "学生" << i << "的姓名:";
char arr[20];
cin.getline(arr, 20);
q[i]->getname(arr);
cout << "输入" << "学生" << i << "的学号:";
cin.getline(arr, 20);
q[i]->getid(arr);
cout << "输入" << "学生" << i << "的电话号:";
cin.getline(arr, 20);
q[i]->getnumber(arr);
cout << endl;
}
for (i = 0; i < 2; i++) {
cout << "学生"<<i << "的姓名为:";
q[i]->showname();
cout << endl;
cout << "学生" << i << "的学号为:";
q[i]->showid();
cout << endl;
cout << "学生" << i << "的电话号为:";
q[i]->shownumber();
cout << endl;
}
delete[]p;//释放内存
return 0;
}