2016-12-07 70 views
0

我遇到了一本书,其中指出有一些称为助手函数的函数,它们通常在类之外声明并包含一些在程序中重复使用的功能。外部助手函数声明?

他们说==和!=是用于比较类的帮助函数的类型。

他们为什么在课堂外宣布?我不明白?

+4

如果您声明例如: 'operator =='作为成员函数,那么类对象* always *必须位于运算符的左侧。 –

回答

2

如果我理解你是对的,你说的是朋友功能。运算符==和运算符!=可以写在类体外,它们的目的是为你的类重载==和!=运算符,因此你可以在if/while等语句中比较它们。例如:

class A { 
    int size; 
public: 
    A(int x) : size(x) {}; 
    // declaring that this operator can access private methods and variables of class A 
    friend operator==(const A&, int); 
    friend operator==(const A&, const A&); 
} 

// overloaded operator for comapring classes with int 
bool operator==(const A& lside, int rside) { 
    return lside.size == rside; 
} 

// second overload for comapring structure two classes 
bool operator==(const A& lside, const A& rside) { 
    return lside == rside.size; // we can also use first operator 
} 

int main() { 
    A obj(5); 
    if (A == 5) { ... } // TRUE 
    if (A == 12) { ... } // FALSE 
} 

如果这不是你的意思,那么也可能有一个经典的非成员函数,任何类都可以使用。正如你所说,这可能对你的程序的多个部分中使用的函数非常有用,而不是绑定到任何特定的类。例如:

// simple function returnig average of given numbers from vector 
int average(const std::vector<int>& vec) { 
    int sum = 0; 
    for (int i : vec) 
     sum += i; 
    return sum/vec.size(); 
}