我试着写了些东西,但是我不知道代码出了什么问题。我的类有一个静态成员、默认构造函数和一个重载的构造函数。
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();
我原以为,由于我正在调用重载的构造函数,它还是会将指针添加到向量中。但是,很明显这并没有发生。
有人能解释一下发生了什么吗?
顺祝商祺,
Bob
Remote() { Remote(1); }
是做什么的? - ChadRemote(1)
在构造函数的 body 中被调用,所以它 不是 被委托的,而是创建了一个立即超出作用域的临时对象。 - ChadRemote& operator=(const Remote&)
和Remote(const Remote&)
。对于第一个函数,目前似乎=default
就可以了。而对于第二个函数,则应该加上channels.push_back(this);
。还有两个移动版本需要考虑:Remote& operator=(Remote&&)
和Remote(Remote&&)
。 - Jarod42