英文:
How can access members derived from a class template in the derived class?
问题
我试图弄清楚如何在派生类中访问基类模板的成员。
我有一个基类模板和一个派生类,如下所示。
template<int dim>
class base_class
{
public:
base_class() = default;
int member_ = 0;
};
template<int dim>
class derived_class : public base_class<dim>
{
public :
derived_class() : base_class<dim>::member_(1) {}
};
int main(int argc, char* argv[])
{
derived_class<2> dc;
return 0;
}
我阅读了(https://stackoverflow.com/questions/4643074/why-do-i-have-to-access-template-base-class-members-through-the-this-pointer),其中指出我必须将派生类的成员前缀为
base_class<dim>::member_.
然而,编译器报错如下:
error: no type named ‘member_’ in ‘class base_class<2>’ derived_class() : base_class<dim>::member_(1) {}
我不明白为什么。有人能帮帮我吗?
英文:
I am trying to figure out how I can access the members of a base template class inside the derived class.
I have a base template class and a derived class as shown below.
template<int dim>
class base_class
{
public:
base_class() = default;
int member_ = 0;
};
template<int dim>
class derived_class : public base_class<dim>
{
public :
derived_class() : base_class<dim>::member_(1) {}
};
int main(int argc, char* argv[])
{
derived_class<2> dc;
return 0;
}
I read (https://stackoverflow.com/questions/4643074/why-do-i-have-to-access-template-base-class-members-through-the-this-pointer) that I must prepend the member of the derived class as
base_class<dim>::member_.
However the compiler gives the following error:
error: no type named ‘member_’ in ‘class base_class<2>’ derived_class() : base_class<dim>::member_(1) {}
I do not understand why. Can anybody help me?
答案1
得分: 1
你应该将基类成员的初始化工作委托给基类构造函数。实现这一点的一种方法如下所示。
如图所示,添加了一个带参数的构造函数 base_class<int>::base_class(int)
用于初始化基类成员。然后在派生类的 成员初始化列表 中使用了新增的带参数构造函数。
template<int dim>
class base_class
{
public:
base_class() = default;
int member_ = 0;
//添加了这个带参数的构造函数
base_class(int p): member_(p){}
};
template<int dim>
class derived_class : public base_class<dim>
{
public :
//使用新增的带参数构造函数
derived_class() : base_class<dim>(1)
{
}
};
我还建议阅读 How can I initialize base class member variables in derived class constructor?。
英文:
You should delegate the work of initialization of base member to base class constructor. One way of doing that is as shown below.
As can be seen, a parameterized ctor base_class<int>::base_class(int)
has been added to initialize the base member. Then the newly added parametrized ctor is used in the member initializer list of the derived class.
template<int dim>
class base_class
{
public:
base_class() = default;
int member_ = 0;
//added this parameterized ctor
base_class(int p): member_(p){}
};
template<int dim>
class derived_class : public base_class<dim>
{
public :
//use the newly added parameterized ctor
derived_class() : base_class<dim>(1)
{
}
};
I would also recommend reading How can I initialize base class member variables in derived class constructor?.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论