这个问题在这里已经有了答案:
Why do I have to access template base class members through the this pointer?
(3 个回答)
2年前关闭。
我正在编写一个通用的 Vector 类,我希望 Vector3 类从 Vector 继承。 Vector 的数据可以是任意长度,Vector3 的数据长度为 3。所以我想为 Vector3 创建一个不同的构造函数来访问 Vector 的数据和长度。对于这个问题,我简化了代码。
#include <iostream>
template <typename T>
class A {
protected:
T value;
public:
A()
: value(0)
{};
A(T value)
: value(value)
{};
~A ()
{};
T get_value()
{
return value;
}
};
template <typename T>
class B : public A<T> {
public:
B()
: A<T>(3)
{};
T test()
{
return value; // error: 'value' was not declared in this scope
}
};
正如我所说,我想访问子类“B”中的“值”,但是我收到了错误通知
error: 'value' was not declared in this scope
但是根据 c++ 网站( http://www.cplusplus.com/doc/tutorial/polymorphism/ ),我应该能够访问“值(value)”。
为什么会这样,更重要的是,我该如何解决这个问题?
最佳答案
这是 C++ 的一个难点。由于您继承自 A<T>
,而不是 A
,成员名称默认不可见。它们被称为非依赖名称,因为它们不依赖于模板参数。我通常会导入我想明确使用的成员:
template <typename T>
class B : public A<T> {
using A<T>::value;
public:
B()
: A<T>(3)
{};
T test()
{
return value; // error: 'value' was not declared in this scope
}
};
关于C++ - 使用父类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59911036/