C语言的构造函数和静态成员如何改写成一个长尾词的?
- 内容介绍
- 文章标签
- 相关推荐
本文共计438个文字,预计阅读时间需要2分钟。
我在尝试一些新东西,不知道代码怎么回显。有一个类,它有一个静态成员和一个默认构造函数及一个加载的函数。+class Remote{public: static std::vector channels; static void interrupt(){ for (Remote*r
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"; }
请在此处查看示例:ideone.com/ahauPV
本文共计438个文字,预计阅读时间需要2分钟。
我在尝试一些新东西,不知道代码怎么回显。有一个类,它有一个静态成员和一个默认构造函数及一个加载的函数。+class Remote{public: static std::vector channels; static void interrupt(){ for (Remote*r
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"; }
请在此处查看示例:ideone.com/ahauPV

