C构造函数和静态成员
发布时间:2020-12-16 09:22:00 所属栏目:百科 来源:网络整理
导读:我正在尝试一些东西,我不知道代码是怎么回事.我有一个类,它有一个静态成员和默认构造函数和一个重载的. class Remote{public: static std::vectorRemote* channels; static void interrupt() { for (Remote* r : channels) { r-ProcessInterrupt(); }; } voi
我正在尝试一些东西,我不知道代码是怎么回事.我有一个类,它有一个静态成员和默认构造函数和一个重载的.
class Remote { public: static std::vector<Remote*> channels; static void interrupt() { for (Remote* r : channels) { r->ProcessInterrupt(); }; } void ProcessInterrupt() { std::cout << "ProcessInterrupt called."; }; Remote(const int a) { std::cout << "Remote(const int a) called.n"; channels.push_back(this); } Remote() { Remote(1); std::cout << "Remote() called.n"; } ~Remote() { std::vector<Remote *>::iterator ch = std::find(channels.begin(),channels.end(),this); if (ch != channels.end()) { channels.erase(ch); }; } }; 在main.cpp中,我声明了Remote类的两个实例.我现在注意到的是,如果我使用默认构造函数实例化它们,则指针不会添加到向量中.然后我尝试使用重载的构造函数,它确实将它添加到向量. Remote r1 = Remote(); Remote r2 = Remote(1); std::cout << Remote::channels.size() << "n"; Remote::interrupt(); 我希望,因为我正在调用重载的构造函数,它仍然会添加指向向量的指针.然而,这显然没有发生. 谁能解释一下发生了什么? 亲切的问候, 短发 解决方法
构造函数
Remote() { Remote(1); std::cout << "Remote() called.n"; } 不向通道向量添加任何内容.在此上下文中,Remote(1)不是委托构造函数. 试试这个: Remote() : Remote(1) { std::cout << "Remote() called.n"; } 请在此处查看示例:https://ideone.com/ahauPV (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |