static 的使用
-名称解释:static 表示静态的意思,使用static 修饰的类的成员变量或者成员函数,该变量或函数是属于类,而不属于具体对象;调用该成员变量或函数的时候要加上相应的类名。
具体代码:
#pragma once
#include <string>
using namespace std;
class Student
{
public:
Student(string name,int age);
~Student();
void PrintInfo(void);
static void SetSchool(string& s);
private:
string name;
int age;
static string school;
};
#include "Student.h"
#include <iostream>
using namespace std;
Student::Student(string name, int age)
{
this->name = name;//含有this
this->age = age;
}
Student::~Student()
{
}
void Student::PrintInfo(void)
{
cout << "school is " << school << endl;
cout << "name is " << name << endl;
cout << "age is " << age << endl;
}
string Student::school = "chengdu";//只能在.c文件中声明
void Student::SetSchool(string& s)
{
school = s;
}
#include <map>
#include <string>
#include <iostream>
#include "Student.h"
using namespace std;
int main()
{
Student A("a", 7);
A.PrintInfo();
//Student::SetSchool("beijing");// compile err 参数为 const char [8] 类型
string s = "beijing";
Student::SetSchool(s);//出处必须要用string 引用
A.PrintInfo();
getchar();
return 0;
}