【问题标题】:Friend function have no access to struct member declared in class templateFriend 函数无权访问类模板中声明的结构成员
【发布时间】:2022-01-03 11:34:55
【问题描述】:

情况如下:

template <class T>
class A {
    struct S {
        /* some data */
    }
    S some_member;
public:
    /* some methods */
    friend bool B (S);
};
 
bool B (S s) { //<-- ERROR "S was not declared in this scope"
    /* do something */
}

我应该怎么做才能正确编译程序?

【问题讨论】:

  • 请在问题中包含错误信息。您当前的问题似乎是您想要A&lt;some_type&gt;::S 而不是S
  • 如果A 不是模板,你也会遇到类似的问题,所以先解决这个问题。

标签: c++ class struct friend


【解决方案1】:

在编写函数B的参数时你必须是

  1. 类模板范围A&lt;&gt;和,
  2. 还指定“某种类型”,如int(或float 等),如下所示:
bool B (A<int>::S s) { //<-- Added change here
    
    return true;
}

你也可以使用其他类型,我已经举了int的例子。

此外,您需要将S 设为公开,并在struct S 定义后添加缺少的分号;

【讨论】:

  • 请注意,S 是私有的,不仅因为您的答案中的代码并不是 OP 代码需要更改的全部
  • @463035818_is_not_a_number 是的,我认为这很明显,OP 可以自己解决。此外,OP 缺少;,我现在在答案末尾提到了它。
猜你喜欢
  • 2015-06-12
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 2013-05-09
  • 2018-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多