Bob*_*Bob 3 c++ visual-c++ c++11
我正在尝试一些东西,我不知道代码是怎么回事.我有一个类,它有一个静态成员和默认构造函数和一个重载的.
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);
};
}
};
Run Code Online (Sandbox Code Playgroud)
在main.cpp中,我声明了Remote类的两个实例.我现在注意到的是,如果我使用默认构造函数实例化它们,则指针不会添加到向量中.然后我尝试使用重载的构造函数,它确实将它添加到向量.
Remote r1 = Remote();
Remote r2 = Remote(1);
std::cout << Remote::channels.size() << "\n";
Remote::interrupt();
Run Code Online (Sandbox Code Playgroud)
我希望,因为我正在调用重载的构造函数,它仍然会添加指向向量的指针.然而,这显然没有发生.
谁能解释一下发生了什么?
亲切的问候,
短发
构造函数
Remote() {
Remote(1);
std::cout << "Remote() called.\n";
}
Run Code Online (Sandbox Code Playgroud)
不向channels向量添加任何内容. Remote(1)在这种情况下,不是委托构造函数.
试试这个:
Remote() : Remote(1) {
std::cout << "Remote() called.\n";
}
Run Code Online (Sandbox Code Playgroud)
请在此处查看示例:https: //ideone.com/ahauPV
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |