【问题标题】:Nested class of templated class with friend operator, compile error [duplicate]带有友元运算符的模板类的嵌套类,编译错误[重复]
【发布时间】:2013-02-25 09:40:27
【问题描述】:

当我尝试编译这个 (g++) 时:

template<typename T>
struct A {

    struct B { };

    template<typename S>
    friend A<S>& operator +(A<S> const &, A<S> const &);
};

template<typename T>
A<T>& operator +(A<T> const &a, A<T> const &b) {
    A<T>::B *x;
    return a;
}

main() { }

我明白了

test.cpp: In function "A<T>& operator+(const A<T>&, const A<T>&)":
test.cpp:12:11: error: "x" was not declared in this scope

为什么?

[忽略:如果我不包括这一行,堆栈溢出说我保存时帖子中有太多代码]

【问题讨论】:

  • B 是依赖类型,使用typename A&lt;T&gt;::B *x;stackoverflow.com/questions/610245/…
  • main() { }A?这不是有效的 C++。
  • 你在声明中使用S,在operator+的定义中使用T
  • 粘贴错误。固定的。 (@Joachim)

标签: c++ templates compiler-errors nested-class


【解决方案1】:

编译器不知道A&lt;T&gt;::B 表示一个类型,因此它会尝试在那里进行乘法运算。

使用typename A&lt;T&gt;::B *x;

【讨论】:

  • 感谢您的修复和奖金解释。
猜你喜欢
  • 2023-03-11
  • 2011-05-08
  • 2013-09-20
  • 2021-05-18
  • 2011-06-07
  • 2010-11-20
相关资源
最近更新 更多