14静态成员变量,静态成员函数,常成员方法

静态成员变量,静态成员函数,常成员方法

  • 静态成员变量是类级别共享的,都可以用类名作用域来调用或查询。
  • 静态成员变量不属于类对象在类中声明,在类外定义。相当于一个以类为作用域的全局变量。
  • 静态成员函数没有 this 指针,只能访问静态成员变量和静态成员函数。
class Date {
public:
    Date(int y, int m, int d);
private:
    int _year;
    int _month;
    int _day;
};

Date::Date(int y, int m, int d) :
    _year(y), _month(m), _day(d)
{}

class Goods {
public:
    Goods(const char* name, int amount, double price, int y, int m, int d);
    static int getNum() {
        return _num;
    }
private:
    char* _name;
    int _amount;
    double _price;
    Date date; 
    static int _num;
};
int Goods::_num = 0;
Goods::Goods(const char* name, int amount, double price, int y, int m, int d) :
    _amount(amount),
    _price(price),
    date(y, m, d)
{
    _num++;
    _name = new char[strlen(name) + 1];
    strcpy(_name, name);
}

int main() {
    Goods good1("nn", 100, 20.0, 2000, 3, 7);
    Goods good2("nn", 100, 20.0, 2000, 3, 7);
    Goods good3("nn", 100, 20.0, 2000, 3, 7);
    Goods good4("nn", 100, 20.0, 2000, 3, 7);
    cout << Goods::getNum() << endl;
    cout << good4.getNum() << endl; //也可以
    return 0;
}
  • 如何保护const变量的指针?
  • 下述show方法由于使用了this指针,所以产生类型转换冲突。
  • 常成员方法:函数后加入const限定符,相当于给this指针加上const限定符。
  • 只要是只读成员的方法,都要实现成常成员方法,常成员方法对对象只能读不能写。
class Goods {
public:
    Goods(const char* name, int amount, double price, int y, int m, int d);
    void show() {
        cout << _name << '\\' << _amount << '\\' << _price << '\\' << endl;
    }
    void cshow() const{ //会给this指针加上const限定符
        cout << _name << '\\' << _amount << '\\' << _price << '\\' << endl;
    }
......
};
int main() {

    const Goods good1("nn", 100, 20.0, 2000, 3, 7);
    good1.show(); //不可以,此过程隐式将const Goods*转换为Goods*,这是不被允许的(this指针类型为Goods*)
    good1.cshow(); //可以
    return 0;
}- 
posted @ 2024-01-16 10:45  SIo_2  阅读(12)  评论(0)    收藏  举报