C++ static使用

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;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值