c++ - friend 模板定义。何时何地包含 <T>?

标签 c++ templates inheritance friend

我想我只需要另一双眼睛来找出我做错了什么。

这是错误:

bfgs_template.hpp:478:5: error: ‘di’ was not declared in this scope
bfgs_template.hpp:478:8: error: ‘b’ was not declared in this scope

这是代码的快照:

template<typename T>
void update_d();

template<typename T>
class BFGSB: public BFGS<T>{
protected:
  double *di;
  int b;
public:
  friend void update_d<T>();
};


template<typename T>
void update_d(){
    di[b] = 0.0; 
}

顺便说一句。虽然我没有发布其余代码。 di 已初始化,如果我使 update_d 成为该类的成员。一切运行顺利。

最佳答案

仅仅因为update_dBFGSB的友元,并不意味着它只能访问dib。就像其他任何函数一样,它是一个非成员函数。它不与 BFGSB 的任何特定实例相关联,因此没有特定的 dib 对象可供访问。将其设为好友意味着允许访问BFGSB 对象的dib 成员。例如,它可以这样做:

template<typename T>
void update_d(){
    BFGSB<T> obj; // We can access the privates of this object
    obj.di[obj.b] = 0.0; 
}

关于c++ - friend 模板定义。何时何地包含 <T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16257176/

相关文章:

c++ - 理解-Weffc++

jQuery .template 和 .tmpl 无法正常工作

json - Spring boot中Json Response的继承

c++ - 在 C++ 中创建对象时出现 "Unresolved External Symbol"错误

c++ - Linux 上的 Qt - 版本冲突?

c++ - KeyboardProc 回调函数没有被调用?

c++ - 在单独的线程中调用 boost::python::object 作为函数

angular - 作为 Angular2 组件的 Typescript 泛型类

c++ - 使用模板传递时访问 vector 元素

C++:为什么我的 DerivedClass 的构造函数无法访问 BaseClass 的 protected 字段?