從今天開始複習C++了,要把之前的知識都回想起來。
做題庫裏的大題找找感覺
1.基本操作題目
#include<iostream>
using namespace std;
class StudentInfo
{
protected:
// ERROR **********found**********
char *Name;
int Age;
int ID;
int CourseNum;
float Record;
public:
StudentInfo(char *name, int Age, int ID, int courseNum, float record);
// ERROR **********found**********
~StudentInfo() {}
float AverageRecord(){
return Record/CourseNum;
}
void show()const{
cout<<"Name: "<<Name<<" Age: "<<Age<<" ID: "<<ID
<<" CourseNum: "<<CourseNum<<" Record: "<<Record<<endl;
}
};
// ERROR **********found**********
StudentInfo::StudentInfo(char *Name, int Age, int ID, int CourseNum, float Record)
{
Name = name;
Age = age;
this->ID = ID;
CourseNum = courseNum;
Record = record;
}
int main()
{
StudentInfo st("Smith",21,99999,12,970);
st.show();
return 0;
}
2.簡單應用題
#include <iostream>
using namespace std;
class vehicle
{
private:
int MaxSpeed;
int Weight;
public:
//**********found**********
vehicle(int maxspeed, int weight) :MaxSpeed(maxspeed), Weight(weight) {};
~vehicle(){};
int getMaxSpeed() { return MaxSpeed; }
int getWeight() { return Weight; }
};
//**********found**********
class bicycle : virtual public vehicle
{
private:
int Height;
public:
bicycle(int maxspeed, int weight, int height):vehicle(maxspeed, weight),Height(height){}
int getHeight(){ return Height; };
};
//**********found**********
class motorcar : virtual public vehicle
{
private:
int SeatNum;
public:
motorcar(int maxspeed, int weight, int seatnum):vehicle(maxspeed, weight),SeatNum(seatnum){}
int getSeatNum(){ return SeatNum; };
};
//**********found**********
class motorcycle : public bicycle,public motorcar
{
public:
motorcycle(int maxspeed, int weight, int height):
vehicle(maxspeed, weight),bicycle(maxspeed, weight,height),motorcar(maxspeed, weight, 1){}
};
void main()
{
motorcycle a(80,150,100);
cout<<a.getMaxSpeed()<<endl;
cout<<a.getWeight()<<endl;
cout<<a.getHeight()<<endl;
cout<<a.getSeatNum()<<endl;
}
3.綜合應用題目
#include "CDeepCopy.h"
#include<fstream>
CDeepCopy::~CDeepCopy(){ delete [] p; }
CDeepCopy::CDeepCopy(int k) { n=k; p=new int[n]; } //構造函數實現
CDeepCopy& CDeepCopy::operator=(const CDeepCopy& r) //賦值運算符函數實現
{
//********333********
n = r.n;
delete[]p;
p = new int[n];
for (int i = 0;i < n;i++)
p[i] = r.p[i];
return *this;
//********666********
}
int main()
{
CDeepCopy a(2),d(3);
a.p[0]=1; d.p[0]=666; //對象a,d數組元素的賦值
{
CDeepCopy b(3);
a.p[0]=88; b=a; //調用賦值運算符函數
cout<<b.p[0]; //顯示內層局部對象的數組元素
}
cout<<d.p[0]; //顯示d數組元素a.p[0]的值
cout<<" d fade away;\n"; cout<<a.p[0]; //顯示a數組元素a.p[0]的值
writeToFile("");
return 0;
}
void writeToFile(char *path)
{
char filename[30];
strcpy(filename,path);
strcat(filename,"out.dat");
ofstream fout(filename);
CDeepCopy a(2),b(3),d(3);
a.p[0]=1;b.p[0]=66;d.p[0]=222;
a=b;
fout<<a.p[0];
fout<<d.p[0]<<" d fade away;\n"<<b.p[0];
}