有没有办法在C++基类中创建一个"虚拟"变量?

jac*_*ill 8 c++ oop c++11

我有一个带有指针的基类,需要在所有子类的构造函数中进行特定的初始化.如何确保在子类的构造函数中初始化此变量?我基本上想要与制作纯虚函数相同的功能,除了指向对象的指针.有没有办法做到这一点?

我的代码看起来像这样:

A.hpp:

class A {
protected:
    A();
    X *pointer;
};
Run Code Online (Sandbox Code Playgroud)

B.hpp:

class B : public A {
public:
        B();
};
Run Code Online (Sandbox Code Playgroud)

B.cpp:

B::B() : A() {
    // how do i make sure pointer gets initialized here?
}
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这个目标?

Jar*_*d42 11

更改基类的构造函数:

class A {
protected:
    explicit A(X* pointer);
    X *pointer;
};
Run Code Online (Sandbox Code Playgroud)

所以孩子必须给予价值,如:

class B : public A {
public:
        B() : A(nullptr) {}
        explicit B(X* x) : A(x) {}
};
Run Code Online (Sandbox Code Playgroud)


Ben*_*igt 5

只需为基类构造函数定义参数:

class A {
protected:
    A(X* ptr) : pointer(ptr) {}
    X *pointer;
};
Run Code Online (Sandbox Code Playgroud)

然后派生类需要在其ctor-initializer列表中传递它们:

B::B() : A(/* value of pointer must be passed here*/)
{
}
Run Code Online (Sandbox Code Playgroud)