如何将静态成员的范围限制为特定类?例如,如果我创建 A 类的 a1 对象和 A 类的 a2 对象,我希望这些对象(使用 A 创建的 a1、a2)可以为其静态成员具有不同的值,但它们对应的派生类具有相同的值。
class A{
public:
A(int member){
A::mMember=member;}
void set(int member){
A::mMember=member;}
int get(){
return A::mMember;}
protected:
static int mMember;
};
int A::mMember;
class B:public A{
public:
B(int member):A(member){};
};
class C:public A{
C(int member):A(member){};
};
int main()
{
A * a1= new A(1);
std::cout<<"a1: "<< a1->get()<<std::endl;
B * b1= new B(2);
std::cout<<"a1: "<< a1->get()<<std::endl;
// How to make a1 continue be a1=2 and a2 = 5. I mean how to limit a static member
//to only its derivated class
A * a2 = new A(5);
std::cout<<"a1: "<< a1->get()<<std::endl;
std::cout<<"a2: "<< a2->get()<<std::endl;
}