Static Members:

Static Members:

c++中一些静态成员函数的有趣的事实

  • 静态成员函数没有this指针
class Test{
private:
public:
    static Test *fun() {
        return *this;//compiler error
    }
};
  • 静态成员函数不能是虚函数

  • 成员函数名相同且参数相同,如果其中一个是静态成员函数,那么他们就不能重载

class Test{
private:
public:
    static void fun();
    void fun();
};
  • 静态成员函数不能被声明为const,const volatile,volatile
class Test{
private:
public:
    static void fun() const{return;}
};

C++中静态成员

  • 1

class A{
private:
public:
    A() { cout << "A's constructer is called" << endl; }
};

class B{
private:
    static A a;
public:
    B() { cout << "B's constructer is called" << endl; }
};


int main() {
    B b;

    return 0;
}

这里写图片描述

这里仅仅调用B的构造函数,原因是静态成员变量必须在类声明中被声明,而不是定义。他们还必须在类外用范围解析符(::)定义


如果尝试不定义就使用静态成员变量,编译出错
如下:

  • 2
class A{
private:
    int x;
public:
    A() { cout << "A's constructer is called" << endl; }
};

class B{
private:
    static A a;
public:
    B() { cout << "B's constructer is called" << endl; }
    static A getA() { return a; }
};


int main() {
    B b;
    A a = b.getA();
    return 0;
}

编译出错

  • 3
class A{
private:
    int x;
public:
    A() { cout << "A's constructed is called " << endl; }
};

class B{
private:
    static A a;
public:
    B() { cout << "B's constructed is called " << endl; }
    static A getA() { return a; }
};

A B::a;

int main() {
    B b1,b2,b3;
    A a = b1.getA();
    return 0;
}

这里写图片描述

注意,这里B调用三次,而A调用一次,这是因为a是静态成员变量,为所有对象共享;另外静态成员变量可以不需对象即可访问。


补充,其实静态成员在main函数之前就已经被调用了,即在定义静态对象的时候,其已经生成。

class A{
private:

public:
    A() { cout << "a's constructor called" << endl; }
};

class B{
private:
    static A a;
public:
    B() { cout << "b's constructor called" << endl; }
    static A getA() { return a; }
};

A B::a;

int main() {
    return 0;
}

输出

这里写图片描述

  • 4
class A{
private:
    int x;
public:
    A() { cout << "A's constructed is called " << endl; }
};

class B{
private:
    static A a;
public:
    B() { cout << "B's constructed is called " << endl; }
    static A getA() { return a; }
};

A B::a;

int main() {
    A a = B::getA();
    return 0;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值