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

时间:2018-10-09 18:13:33

标签: c++ c++11 visual-c++

我正在尝试某些东西,但我不知道代码在做什么。我有一个类,它具有一个静态成员和默认构造函数以及一个重载的类。

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();

我希望,由于我正在调用重载的构造函数,因此仍会向矢量添加指针。但是,这显然没有发生。

谁能解释发生了什么事?

亲切的问候,

鲍勃

1 个答案:

答案 0 :(得分:6)

构造函数

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

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

尝试以下方法:

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

在此处查看示例:https://ideone.com/ahauPV

相关问题