C++构造函数和静态成员

C++ Constructors and static members

本文关键字:静态成员 构造函数 C++      更新时间:2023-10-16

我正在尝试一些东西,我不知道代码是怎么回事。我有一个类,它有一个静态成员和一个默认构造函数和一个重载的构造函数。

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";
}

不会向channels向量添加任何内容。在此上下文中,Remote(1)不是委托构造函数。

试试这个:

Remote() : Remote(1) {
std::cout << "Remote() called.n";
}

请参阅此处的示例:https://ideone.com/ahauPV