上机4

本文通过三个部分展示了C++中类和对象的使用。partA探讨了函数参数传递时对象状态的不变性;partB介绍了类作为参数时的指针行为;partC讲解了静态成员变量在类中的共享特性,并在实际操作中展示了如何使用静态成员进行数据管理。通过对这些概念的实例解析,加深了对C++类和对象的理解。
摘要由CSDN通过智能技术生成

//part a
#include
using namespace std;
class tr {
public:
tr(int n)
{
i = n;
}
void set_i(int n)
{
i = n;
}
int get_i()
{
return i;
}
private:
int i;
};
void sqr_it(tr ob)
{
ob.set_i(ob.get_i() * ob.get_i());
cout << “在函数sqr_it内,形参对象ob的数据成员i的值为:” << ob.get_i();
cout << endl;
}
/void sqr_it(tr ob)
{
ob->set_i(ob->get_i() * ob->get_i());
cout << “在函数sqr_it内,形参对象ob的数据成员i的值为:” << ob->get_i();
cout << endl;
}*/
/void sqr_it(tr& ob)
{
ob.set_i(ob.get_i() * ob.get_i());
cout << “在函数sqr_it内,形参对象ob的数据成员i的值为:” << ob.get_i();
cout << endl;
}
/
int main()
{
tr obj(10);
cout << “调用函数sqr_it前,实参对象obj的数据成员i的值为:”;
cout << obj.get_i() << endl;
sqr_it(obj);
cout << “调用函数sqr_it后,实参对象obj的数据成员i的值为:”;
cout << obj.get_i() << endl;
return 0;
}
//part b
#include
using namespace std;
class Ctest {
static int count;
public:
Ctest() {
++count;cout << “对象数量=” << count << ‘\n;’;
}
};
int Ctest::count = 0;
int main(void) {
Ctest a[3];
return 0;
}
//part c
#include
using namespace std;
class TStudent {
static float m_ClassMoney;
public:
void InitStudent(char name[]) {
cout << “学生姓名为:” << name;
};
void ExpendMoney(float money) {
m_ClassMoney = m_ClassMoney - money;
};
void ShowMoney() {
cout << “班费还剩余” << TStudent::m_ClassMoney << ‘\n’;}
};
float TStudent::m_ClassMoney = 1000;
int main() {
char name_a[10] = “A”;
char name_b[10] = “B”;
char name_c[10] = “C”;
TStudent A, B, C;
A.InitStudent(name_a);
A.ExpendMoney(50);
A.ShowMoney();
B.InitStudent(name_b);
B.ExpendMoney(98.5);
B.ShowMoney();
C.InitStudent(name_c);
C.ExpendMoney(500.53);
C.ShowMoney();
return 0;
}
1.part A 中表明在函数中修改参数变量,变量本身不改变。
2.part B表明使用对象做参数时,可以当做指针来使用。
3.part C
debug过程:
(1)在构造函数时,需要在函数名前加返回参量的类型。
(2)在ShowMoney函数中输出时,必须加上类名和域作用符。TStudent ::m_Claas money.
(3)需要注意在初始化静态变量时,是在类外定义。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值