| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 517 人关注过本帖
标题:本人自学C,现在自学C++,里面有个静态成员函数没弄明白
只看楼主 加入收藏
lyj23
Rank: 3Rank: 3
等 级:论坛游侠
帖 子:168
专家分:140
注 册:2010-10-31
结帖率:86.21%
收藏
已结贴  问题点数:10 回复次数:3 
本人自学C,现在自学C++,里面有个静态成员函数没弄明白
书上的例题:
程序代码:
#include<iostream>
using namespace std;
class Student
{
public:
  Sudent(int n,int a,float s):num(n),age(a),score(s){}
  void total();
  static float average();
private:
  int num;
  int age;
  float score;
  static float sum;
  static float count;
};
void Student::total()
{
  sum+=score;
  count++;
}
float Student::average()
{return(sum/count);}
float Student::sum=0;
float Student::count=0;
int main()
{Student stud[3]={
  Student(1001,18,70),
  Student(1002,19,78),
  Student(1005,20,98)
};
  int n;
  cout<<"please input the number of students:"<<endl;
  cin>>n;
  for(int i=0;i<n;i++)
    stud[i].total();
  cout<<"the average score of"<<n<<"students is"<<Student::average()<<endl;
  return 0;
}
这里有几个问题:
average函数如果定义为非静态成员函数行不行?
程序能否通过编译?
需要作什么修改?
为什么要用静态成员函数?

高手来啊!!
搜索更多相关主题的帖子: average 自学 
2011-03-27 17:18
yuccn
Rank: 16Rank: 16Rank: 16Rank: 16
来 自:何方
等 级:版主
威 望:167
帖 子:6815
专家分:42393
注 册:2010-12-16
收藏
得分:10 
1 average可以定义成非静态函数,本来静态函数和非静态函数就没有什么本质的区别,区别只是非静态函数多传了一个this的参数。

2 void Student::total()
{
  sum+=score;
  count++;
}
这个函数存在问题,他不应该改变sum和count的值
3 用静态成员,函数的主要原因是因为其数据不属于对象的,而属于模板的

还是先打好点c++的基础吧,这些都是必需要理解的

我行我乐
公众号:逻辑客栈
我的博客:
https://blog.yuccn. net
2011-03-28 12:13
Ghost_Knight
Rank: 2
等 级:论坛游民
帖 子:19
专家分:10
注 册:2010-9-25
收藏
得分:0 
学习下
2011-03-28 15:41
xu420555701
Rank: 1
来 自:湖南常德
等 级:新手上路
帖 子:2
专家分:0
注 册:2011-3-28
收藏
得分:0 
  学习
2011-03-28 17:09
快速回复:本人自学C,现在自学C++,里面有个静态成员函数没弄明白
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.012491 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved