c++ static

这个是c++很基础的东西,等用到时又有点晕,翻开primer

/*
1.static不能声明成const和虚函数
2.const static可以初始化,但还是需要在类外定义
3.类的static必须定义并且在类外定义,把内存分配在静态存储区,如果只声明不定义出现无法解析的外部命令
我猜是他是在编译时期分配内存的,所以要定义,有点全局变量的感觉,你就想成全局变量,只是有了一些类的属性而已
*/
#include <iostream>
using namespace std;
class Account {
public:
    // interface functions here
    void applyint() { amount += amount * interestRate; }
    static double rate() { return interestRate; }
    static void rate(double); // sets a new rate
private:
    std::string owner;
    double amount;
    static double interestRate;
    static double initRate();
};

double Account::interestRate;
void Account::rate(double newRate)//无需指定static,该保留字只出现在类定义内部的声明处 { interestRate = newRate; } int main() { Account ac1; Account* ac2 = &ac1; double rate; rate = ac1.rate();//类对象访问 rate = ac2->rate();//类指针访问 rate = Account::rate();//类访问 getchar(); }
虽然还是有点晕,暂时不研究了
原文地址:https://www.cnblogs.com/zzyoucan/p/3717964.html