【问题标题】:Why does the child class not see the parent's typedef struct in C++?为什么子类在 C++ 中看不到父类的 typedef 结构?
【发布时间】:2012-08-15 17:18:44
【问题描述】:

我最近遇到了一些 C++ 代码,在父类中 typedefed a struct。但是,它似乎在子类中不可用,即使它没有标记为private(它是protected)。我在下面创建了一个最小的工作示例(如下)来演示此失败。我已经公开了所有内容,但仍然失败。给出的错误是(使用g++):

B.h:8: error: expected ',' or '...' before '&' token
B.h.8: error: ISO C++ forbids declartion of 'Datum' with no type

A.h(编译)

template<typename S, typename T> class A {
public:
    typedef struct {
        S x;
        T y;
    } Datum;
};

B.h(不编译)

#include "A.h"
template<typename Q> class B : public A<Q, Q> {
public:
    void output(const Datum& dat);
};

B.h(编译)

#include "A.h"
template<typename Q> class B : public A<Q, Q> {
public:
    typedef struct {
        Q x;
        Q y;
    } Datum;
    void output(const Datum& dat);
};

为什么B.h 的第一个版本无法编译?第二个是安全的选择吗?有没有更好(更简洁或惯用)的方法来处理这个问题?

【问题讨论】:

  • 我相信A.h 确实按书面方式编译。
  • @KerrekSB 谢谢。我处于无法复制和粘贴的情况,所以我犯了一个错误。现已修复。
  • @BoPersson 答案是相关的,但我想说这个问题不是重复的,因为如果我知道这个问题有多密切相关,我可能已经知道我的解决方案了。 IE。我想说答案相似,但问题不同。
  • @Kazark - 这是一个见仁见智的问题。 :-) 关于为什么来自模板化基类的名称不可见有很多问题——都是出于同样的原因。链接到问题的typedef 与此相同,但问题很普遍。

标签: c++ templates inheritance name-lookup


【解决方案1】:

您需要在B 中输入typename A&lt;Q,Q&gt;::Datum。由于 base 是一个模板,它的名称是依赖名称,在第一阶段不可见,您需要 typename 指定名称命名一个类型(而不是值或模板)。

您还应该丢失typedef。 C++ 与 C 的工作方式不同,你应该说:

struct Datum { S x; T y };

【讨论】:

  • 你也需要输入typename
【解决方案2】:

这个

typedef struct {
    S x;
    T y;
}

格式不正确。 typedef 需要一个类型和一个“别名”来命名该类型。你可能需要的是

template<typename S, typename T> 
class A {
 public:
    struct Datum { S x; T y; };
};

没有 typedef,这里根本不需要。然后,您需要正确限定Datum 名称,如typename A&lt;Q,Q&gt;::Datum

#include "A.h"
template<typename Q> 
class B : public A<Q, Q> {
 public:
    void output(const typename A<Q,Q>::Datum& dat);
};

【讨论】:

    猜你喜欢
    • 2022-10-20
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 2019-08-14
    • 2023-03-17
    • 2012-01-01
    相关资源
    最近更新 更多