与子构造函数同名的继承类成员
Inherited class member with the same name as child constructor
考虑这个例子:
class Label{
public:
std::string Text;
};
class Text:
public Label
{
public:
Text(std::string text) {}
};
int main()
{
Text text("");
text.Text; //<---- GCC CE: Invalid use of 'class Text'
return 0;
}
class Text:
public Label
{
public:
Text(std::string text) {}
using Label::Text; // doesn't help either
};
如果继承的类成员与子类同名,如何访问继承的类成员?
class Text:
public Label
{
public:
Text(std::string text):
Text::Text(Label::Text){}
std::string &Text;
};
这样的事情能行得通吗?(我知道上面的代码没有。
这是一个工作障碍(这很令人困惑(; 您可以通过基类名称访问基类的数据成员。
例如text.Label::Text;
尽管正确的答案是(由@songyuanyao发布(
text.Label::Text;
我已经想出了如何避免这种奇怪的语法。
使用旧的 C 样式 typedef 进行简单的"黑客"就可以了:
typedef class Text_:
public Label
{
public:
Text_(std::string text){}
}Text;
现在突然代码示例编译。哇......C++魔法...
相关文章:
- 为什么我可以通过SubBase类的公共继承方法打印出基类的私人继承成员
- 派生类调用使用非继承成员的继承函数
- 如果存在具有不同参数的继承成员,为什么对 C++ 结构函数的调用不明确?
- C :原始成员与继承成员的优先级
- 更改继承成员的地址
- C 是否可以不继承成员
- 使用模板的继承阴影继承成员
- 继承成员功能的模板专业化
- 不允许继承成员,为什么
- 派生模板类和继承成员变量的语法谜题
- 继承成员地址的C++标准
- 多级继承成员访问
- 访问专用模板的私有/继承成员变量
- 基模板继承成员,减少所需的类型
- 继承成员函数指针
- 模板专用化类不继承成员
- C++14正在初始化类构造函数初始化列表中的继承成员
- 具有专门初始化的继承成员变量
- 模板继承成员字段
- 访问数据成员的继承成员函数