具有相同字段名称的派生结构

Derived struct with same field names

我有两个结构体 pins1_t & pins2_t 具有相同的字段名称但不同的值。 pins2_t 派生自 pins1_t

namespace pins {
    struct pins1_t {
        int A = 1;
        int B = 2;
        int C = 3;
        int D = 4;
    };

    struct pins2_t : pins1_t {
        int A = 6;
        int B = 7;
        int C = 8;
        int D = 9;
    };
};

我试图通过基本结构引用来访问 pins2_t 中的值,但没有成功。

pins::pins1_t pins1;
pins::pins2_t pins2;

pins::pins1_t* pPins;
pins::pins1_t* pPins2;

pPins = &pins1;
pPins2 = &pins2;

print("Pins %d, Pins2 %d, PPins %d, PPins2 %d", pins1.A, pins2.A, pPins->A, pPins2->A);
The output is: "Pins 1, Pins2 6, PPins 1, PPins2 1"
But should be: "Pins 1, Pins2 6, PPins 1, PPins2 6"

即使我尝试 pins::pins2_t* pPins2,所以我用派生的 class 引用派生的 class 指针,我得到基数 class 的值:/

I'm trying to access the values from pins2_t by referencing via the base struc

您只能通过基础子对象访问基础子对象的成员。您无法访问派生 class 的成员。因此,您无法实现您的目标。

派生 class 中的成员会影响基础 class 中的成员。这几乎不是您想要的(因为正如您所注意到的,它不起作用)。

因为这些只是变量,所以没有必要隐藏子项中的声明 class。只需初始化基础 class 成员:

struct pins1_t {
    int A = 1;
    int B = 2;
    int C = 3;
    int D = 4;
};

struct pins2_t : pins1_t {
    pins2_t() : pins1_t{6, 7, 8, 9} {}
};

(或者,您可以按照 interjay 的建议通过虚函数使用运行时多态性,但目前您的问题中没有任何内容表明这是必要的;并且在没有令人信服的理由的情况下,它是过度设计的。)

看来您需要仔细检查您的解决方案。至少这部分:

Even if I try pins::pins2_t* pPins2, so I reference the derived class pointer with the derived class I get the value of the base class :/

此代码适用于我(Mac OS,g++ 4.2.1 编译器):

  pins1_t pins1;
  pins2_t pins2;

  pins1_t* pPins;
  pins2_t* pPins2; // <-- pointer type fixed here

  pPins = &pins1;
  pPins2 = &pins2;

  printf("Pins %d, Pins2 %d, PPins %d, PPins2 %d", pins1.A, pins2.A, pPins->A, pPins2->A);

输出与您在“应该”部分中所写的相同:

  Pins 1, Pins2 6, PPins 1, PPins2 6

最简单的方法是使用dynamic_cast。但是您需要至少定义一个虚函数才能使这种方式工作。参见 C++ inheritance downcasting

另一方面,为了使用指向基 class 的指针访问派生的 class 字段而不使用标准 dynamic_cast 方式,可以使用 static_cast甚至 reinterpret_cast。但这似乎是一个肮脏的黑客。除非你知道自己在做什么,否则不要使用 reinterpret_cast:)