我有一个在类中定义的结构。如何在朋友功能中使用它?

时间:2015-02-04 08:05:19

标签: c++

我正在构建一个类实现,我想使用在用作参数的类中定义的结构。以下是一些有用的代码:

void Polynomial::naivePrint()
{
    //start reading the terms from the beginning
    Term* pos = first;
    //print all of the terms in the polynomial
    while(pos != NULL){
        std::cout << "y=" << pos->coeff << "x^" << pos->power;
        //print a plus until we get to the last term
        if(pos->next != NULL){
            std::cout << "+";
        }
        pos = pos->next;
        }
    std::cout<<endl;
}

我想把它放到一个ostream朋友函数中,所以我尝试了这个:

std::ostream & operator << (std::ostream &out, const Polynomial &Poly)
{
   //start reading the terms from the first term
   Term* pos = Poly.first;
   //print all of the terms in the polynomial
   while(pos != NULL){
       out << "y=" << pos->coeff << "x^" << pos->power;
      //print a plus until we get to the last term
      if(pos->next != NULL){
         out << "+";
      }
      pos = pos->next;
   }
   out<<endl;
}

告诉我‘Term’ was not declared in this scope

所以我尝试了Poly.Term* pos = Poly.first;

其中说invalid use of ‘struct Polynomial::Term’

我是否可以使用参数类中声明的结构类型来声明变量?

1 个答案:

答案 0 :(得分:2)

TermPolynomial内定义,因此在Polynomial::Term类的范围之外使用时,需要使用全名Polinomial来引用它。< / p>

Polynomial::Term* pos = Poly.first;