6.C++的构造函数与析构函数
C++的构造函数与析构函数
1.构造函数
构造函数的函数名与类名相同,通过构造函数的条件可以确定创建对象的条件。
当类中有定义构造函数时,默认的无参构造函数会失效。
示例:(求学生的平均分)
Student.h
#include <iostream>
using namespace std;
class Student{
private:
string stuId;
string stuName;
int score;
static int stuCount,totalScore;
public:
Student(string stuId,string stuName);//构造函数,需要传入学号与姓名才能创建
void setScore(int sc);
string getStuId_Name();
int getScore();
void print();
static int getStuCount();
static float getAvg();
};
int Student::stuCount = 0;
int Student::totalScore = 0;
Student::Student(string stuId,string stuName){
this->stuId = stuId;
this->stuName = stuName;
this->score = 0;
stuCount++;
}
void Student::setScore(int sc){
totalScore = totalScore - this->score + sc;
this->score = sc;
}
string Student::getStuId_Name(){
return this->stuId + " " + this->stuName;
}
int Student::getScore(){
return this->score;
}
void Student::print(){
cout << this->stuId + " " + this->stuName + " 成绩:"
<< this->score
<< " 总分为:" << totalScore
<< endl;
}
int Student::getStuCount(){
return stuCount;
}
float Student::getAvg(){
return totalScore*1.0/stuCount;
}
main.cpp
#include <iostream>
#include "Student.h"
using namespace std;
int main(){
Student stu("1","张三");
Student stu2("2","李四");
Student stu3("3","李华");
stu.setScore(98);
stu.print();
stu2.setScore(60);
stu2.print();
stu3.setScore(45);
stu3.print();
// avg = (stu.getScore()+stu2.getScore()+stu3.getScore())/3.0;
// cout << "平均分为:" << avg <<endl;
cout << "学生人数为:" << Student::getStuCount()
<< " 平均分为:" << Student::getAvg() <<endl;
stu3.setScore(60);
stu3.print();
cout << "学生人数为:" << stu3.getStuCount()
<< " 平均分为:" << stu3.getAvg() <<endl;
return 0;
}
2.析构函数
析构函数声明为名称与类名相同,无参,类名前使用~定义,析构函数是当创建的对象被删除时调用。
实例:(商品的进出货)
Item.h
#include <iostream>
using namespace std;
class Item{
private:
string ID,name;
static int count;
public:
Item(string pID,string pName);
~Item();
static int getCount();
string getID_Name();
};
int Item::count = 0;
Item::Item(string pID,string pName){
ID = pID;
name = pName;
count++;
cout << pName << "商品进货成功!" <<endl;
}
Item::~Item(){
cout << "商品出货成功!" <<endl;
count--;
}
int Item::getCount(){
return count;
}
string Item::getID_Name(){
return ID+" "+name;;
}
main.cpp
#include "Item.h"
int main(){
// 分配静态内存 Item item("1","衣服");
//分配动态内存,才能被delete删除
Item *item = new Item("1","衣服");
Item *item2 = new Item("2","裤子");
Item *item3 = new Item("3","鞋子");
Item *item4 = new Item("4","袜子");
cout << "当前商品总数:" << item->getCount() << endl;
//free(item3);
//cout << "当前商品总数:" << item->getCount() << endl;
cout << "出售了" << item4->getID_Name() << endl;
//delete(item4);
delete item4;
cout << "当前商品总数:" << item->getCount() << endl;
return 0;
}

浙公网安备 33010602011771号