标签:cout const use pos 成员 pause 2.4 src []
普通成员函数能够訪问全部成员变量。而静态成员函数仅仅能訪问静态成员变量。
如:
<pre name="code" class="cpp">
#include<iostream>
#include<string>
using namespace std;
class Student{
private:
string name;
int age;
float score;
static int number; //定义静态成员变量
static float total;
public:
Student(string name,int age,float score);
Student(const Student & s);
~Student();
void setName(string n);
string getName();
void setAge(int a);
int getAge();
void setScore(float s);
float getScore();
void say();
static float getAverage();
};
/*注意。假设构造函数的形參和 类的成员变量名字一样。必须採用 this -> name = name ,而不能够 写成 name = name*/
Student::Student(string name,int age,float score){
this->name = name;
this ->age = age;
this ->score = score;
number++;
total += score;
}
Student::Student(const Student & s){
this ->name = s.name;
this ->age = s.age;
this ->score = s.score;
}
Student::~Student(){}
string Student::getName(){
return this->name;
}
int Student::getAge(){
return this->age;
}
float Student::getScore(){
return this ->score;
}
void Student::setName(string n){
this ->name = n;
}
void Student::setAge(int a){
this ->age =a ;
}
void Student::setScore(float s){
this->score =s;
}
void Student::say(){
cout << this->name <<" : " << this->age <<" : " << this ->score << " : " << Student::number <<endl;
}
float Student::getAverage(){
if(number == 0)
{
return 0;
}
else
return total/number;
}
//静态变量必须初始化。才干够使用
int Student::number = 0;
float Student::total = 0;
int main(int argc,char*argv[])
{
//即使没有创建对象也能够訪问静态成员方法
cout << "没有学生的时候的平均成绩"<< Student::getAverage() <<endl;
Student s1("lixiaolong",32,100.0);
Student s2("chenglong",32,95.0);
Student s3("shixiaolong",32,87.0);
s1.say();
s2.say();
s3.say();
cout << "平均成绩为" << Student::getAverage() <<endl;
system("pause");
return 0;
}
标签:cout const use pos 成员 pause 2.4 src []
原文地址:http://www.cnblogs.com/liguangsunls/p/7281411.html