C ++中的属性继承如何工作? [英] How does Attribute Inheritance in C++ Work?

查看:125
本文介绍了C ++中的属性继承如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您要复制以下Python代码段:

Suppose you wanted to reproduce the following Python snippet:

class Base:
    name = "base"

    def announce(self):
        print(self.name)

class Derived(Base):
    name = "derived"

Base().announce()
Derived().announce()

...将输出:

"base"
"derived"

最初,您可能倾向于编写如下内容:

Initially, you may be inclined to write something like the following:

#include <iostream>
#include <string>

struct Base {
    std::string name = "base";
    void announce() {
        std::cout << name << std::endl;
    }
};

struct Derived : public Base {
    std::string name = "movie";
};

int main() {
    Base().announce();
    Derived().announce();
    return 0;
}

但是这里Derived.name只是阴影Base.name.调用Derived.announce()引用Base.name并显示"base".

But here Derived.name simply shadows Base.name. Calling Derived.announce() references Base.name and prints "base".

有什么办法可以实现这种行为?如果可能的话,最好没有类模板.

Is there any way to implement this behaviour? Ideally without class templates if possible.

推荐答案

C ++不能像Python一样工作(这并不奇怪,毕竟它们是两种非常不同的语言),并且在继承的类中定义的成员变量确实定义与父类变量无关的新变量.

C++ doesn't work like Python (which isn't surprising, they are two very different languages after all), and member variables defined in an inherited class really defines a new variable that is unrelated to the variables of the parent class.

一种可能的解决方案是创建第二个(可能受保护的)Base构造函数,该构造函数将name作为参数,然后Derived类可以使用它来初始化成员:

One possible solution is to create a second (possibly protected) Base constructor which takes the name as an argument, and then the Derived class can use it to initialize the member:

struct Base {
    Base() = default;  // A defaulted default constructor

    std::string name = "base";
    void announce() {
        std::cout << name << std::endl;
    }

protected:
    explicit Base(std::string name)
        : name{ std::move(name) }  // Initialize the member
    {
    }
};

struct Derived : public Base {
    Derived()
        : Base("movie")  // Initialize the base class using the special constructor
    {
    }
};

需要默认的Base默认构造函数,因为如果声明另一个构造函数,编译器将不会自动为您生成默认构造函数.

The default Base default constructor is needed, because if you declare another constructor the compiler won't automatically generate a default constructor for you.

这篇关于C ++中的属性继承如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆