有时候的实验报告很水,但是这次的内容属于能看懂但是编程的时候会出现很多错误,因此中这次作业我的收获还是很多的
实验一
对于各个变量生存期的实验,我把代码粘贴过来,不做解释了,直接期末时候看看复习。
#include<iostream>
using namespace std;
int i=1;
void other(){
static int a=2;
static int b;
int c=10;
a+=2;i+=32;c+=5;
cout<<"other"<<endl;
cout<<"i:"<<i<<" a:"<<a<<" b:"<<b<<" c: "<<c<<endl;
b=a;
}
int main(){
static int a;
int b=-10;
int c=0;
cout<<"main"<<endl;
cout<<"i:"<<i<<" a:"<<a<<" b:"<<b<<" c: "<<c<<endl;
c+=8;
other();
cout<<"main"<<endl;
cout<<"i:"<<i<<" a:"<<a<<" b:"<<b<<" c: "<<c<<endl;
i+=10;
other();
return 0;
}
实验二
定义一个 Cat类,拥有静态数据成员CountOfCats,记录Cat的个体数目;静态成员函数 GetNumOfCats()读取CountOfCats的值。设计程序测试这个类,体会静态数据成员和静态成员函数的用法。
#include<iostream>
using namespace std;
class Cat{
private:
static int CountOfCats;
int x=1;
public:
Cat(){CountOfCats++;}
~Cat(){CountOfCats--;}
static void GetNumOfCats()
{cout<<CountOfCats<<endl;}
static void print(){
cout<<"asd"<<endl;
}
/*static void print2(){
cout<<x<<endl;
}*/
//这样会报错,因为静态函数并不能访问私有成员函数
};
int Cat::CountOfCats=0;
int main(){
Cat a,b,c;
Cat::GetNumOfCats();//通过类名引用,因为静态函数不属于某一个对象,不过也可以通过对象引用
{
Cat d;
d.GetNumOfCats();
}//为了验证析构函数的使用,我在这里定义了一个作用域
Cat::GetNumOfCats();
return 0;
}
实验三
定义Boat和Car两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和。
#include<iostream>
using namespace std;
class Car;//事先声明一下这个类,因为在后面类中会有互相引用
class Boat{
private:
int weight;
public:
friend void change(Boat &a);
friend int totalweight(Boat a,Car b);
//友元函数前面写个friend,然后依旧要定义返回值类型
Boat(int a):weight(a){}; //注意要写冒号,然后变量赋值列表中括号内是传入的形参
};
class Car{
private:
int weight;
public:
friend int totalweight (Boat a,Car b);
Car(int a):weight(a){};
};
int totalweight(Boat a,Car b){
cout<<a.weight+b.weight<<endl;
}
void change(Boat &a){
a.weight=70;
}
/*
因为友元函数不属于任何一个类,因此只需要在类外定义即可,和正常函数一样,不需要再加friend了,可以这么理解:就是说这个函数是某些类的朋友,那么就必须在类中告诉编译器是friend,但是在类外,他就是一个正常使用的函数。
友元函数的作用就是,可以通过这个友元函数来访问类中的私有成员。
*/
int main(){
Boat a(20);
Car b(10);
totalweight(a,b);
change(a);
totalweight(a,b);
return 0;
}
实验四
这个关于文件的include的,第一次写,记录一下
具体代码不用看,我提几点要注意的1.那个是include"文件名",是双引号,不是<>
2.因为我第二个文件已经引用了第一个,所以最后一个就只需要引用一下第二个就可以了,如果既引用第一个,也引用第二个,就会导致重复定义。
#include<iostream>
using namespace std;
class Point{
private :
int x; int y;
public:
Point(int xx,int yy);
void print();//函数声明
};
#include<iostream>
#include"Point.h"
using namespace std;
Point::Point(int xx,int yy){
x=xx;y=yy;
}
void Point::print(){
cout<<x<<y<<endl;
}
#include<iostream>
#include"Point.cpp"
using namespace std;
int main(){
Point a(1,2);
a.print();
return 0;
}