为什么我的子类构造函数没有被调用?

时间:2014-12-06 14:12:34

标签: c++ inheritance constructor

这是一个真正的谜。我创建了一个基类:

Generator.h

class Generator
{
public:
    Generator(int);
    Generator();
    virtual ~Generator() {};
    //more virtual stuff follows
    ...
};

Generator.cpp

Generator::Generator()
{
     //nothing to do here
}

然后我创建了一个子类:

LoopGenerator.h

class LoopGenerator : public Generator
{
public:
    LoopGenerator();
    ~LoopGenerator();
    virtual void add(RandomStripe&);
    ///more stuff follows
    ...
protected:
    unsigned int pointer;
    std::vector<Generator*> stripes;
};

LoopGenerator.cpp

LoopGenerator::LoopGenerator()
{
    pointer = 0;
    stripes = vector<Generator*>();
}
void LoopGenerator::add(Generator* stripe)
{
    stripes.push_back(stripe);
}

然后我尝试创建LoopGenerator实例:

的main.cpp

LoopGenerator gen = LoopGenerator();
gen.add(RandomStripe((unsigned int)seedval, 5,10, 231,231, 0,255, 0,255));

你可以看到我调用了方法.add.add方法称为,但构造函数不是。我实际上认为LoopGenerator()是一个构造函数调用!

这是构造函数中断点的结果:

child constructor not being called

1 个答案:

答案 0 :(得分:0)

在您的代码中调用

LoopGenerator构造函数。问题出在调试器一侧,由于未知原因,不允许在构造函数中放置断点。在构造函数中输出日志消息,您将看到它被调用。 BTW你构建对象的行应该是

LoopGenerator gen;

而不是

LoopGenerator gen = LoopGenerator();

(这是正确的,但不是惯用的,没有必要)。以同样的方式声明

stripes = vector<Generator*>();
构造函数中的

不是必需的,可以在不改变程序含义的情况下省略,

相关问题