我有一个 GolfCourse 类头文件 gcourse.hh,我想为 >>operator 实现运算符重载。我如何在文件 gcourse.cc 的标题之外执行此操作?也就是说,我需要将哪些“词”指向类本身,“GolfCourse::”对于函数来说还不够......?
gcourse.hh:
class GolfCourse {
public:
---
friend std::istream& operator>> (std::istream& in, GolfCourse& course);
gcourse.cc:
---implement operator>> here ---
最佳答案
GolfCourse::
不正确,因为 operator >>
不是 GolfCourse
的成员.这是一个免费功能。你只需要写:
std::istream& operator>> (std::istream& in, GolfCourse& course)
{
//...
return in;
}
friend
只有在计划访问 private
时才需要类定义中的声明或 protected
来自 GolfCourse
的成员.当然,您可以在类定义中提供实现:
class GolfCourse {
public:
friend std::istream& operator>> (std::istream& in, GolfCourse& course)
{
//...
return in;
}
};
关于c++ - 在 C++ 中的类头外部实现运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12663451/