gpt4 book ai didi

c++ - 将静态成员的范围限制为 n 个特定类

转载 作者:行者123 更新时间:2023-11-28 03:19:23 25 4
gpt4 key购买 nike

<分区>

如何将一个静态成员的作用域限制在n个具体的类中?例如,如果我创建 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;

}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com