【问题标题】:friend template definition. Include <T> when and where?朋友模板定义。何时何地包含 <T>?
【发布时间】:2013-04-27 21:46:07
【问题描述】:

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

这是错误:

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 成为该类的成员。一切顺利。

【问题讨论】:

  • 您希望friend 声明发挥什么作用?将对BFGSB 的实例的引用传递给update_d,它将能够对该实例的私有成员进行操作。

标签: c++ templates inheritance friend


【解决方案1】:

仅仅因为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; 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    相关资源
    最近更新 更多