u07s07 - 关于对象中的静态数据成员如何写入到文件?

如果一个类C中有一个静态数据成员 static int x;


c1 和 c2 均为 C 的对象 

那么执行如下代码后

1.fstream fs("out.dat", ios::out|ios::binary);
2.fs.write(reinterpret_cast<char*>(&c1), sizeof(C));
3.fs.write(reinterpret_cast<char*>(&c2), sizeof(C));

out.dat 文件中是否有x的值?


如果有的话,其中保存了几个 x 值的副本?

————来自课件“u07s07 - 讨论”



 因为类的static属于类。所以,先创建一个.dat文件储存的static int类型的x的值为22。
  1. #include<iostream>
  2. #include<fstream>
  3.  
  4. using namespace std;
  5.  
  6.  
  7. class A{
  8.     public:
  9.         static int x;
  10. };
  11.  
  12.  
  13. int A::x = 22
  14.  
  15. int main(){
  16.  
  17.     fstream  erhu;
  18.     erhu.open("char.dat",ios::out|ios::binary);
  19.     A test;
  20.      
  21.     erhu.write(reinterpret_cast<char*>(&test),sizeof(test));
  22.     erhu.close();
  23.  
  24.    
  25.     cout << "x is :" << test1.x;
  26.      
  27.  
  28.  
  29.     return 0;
  30. }


下面从文件中读取,但X设置为11

代码:

  1. #include<iostream>
  2. #include<fstream>
  3.  
  4. using namespace std;
  5.  
  6.  
  7. class A{
  8.     public:
  9.         static int x;
  10. };
  11.  
  12.  int A::x = 11;
  13.   
  14.  
  15. int main(){
  16.  
  17.     fstream  erhu;
  18.      
  19.  
  20.     A test1;
  21.     erhu.open("char.dat",ios::in|ios::binary);
  22.     erhu.read(reinterpret_cast<char*>(&test1),sizeof(test1));
  23.     erhu.close();
  24.      
  25.     cout << "x is :" << A::x;
  26.      
  27.  
  28.  
  29.     return 0;
  30. }
但结果是

证明static类型不能被储存。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值