[英]operator overloading(using binaray friend function) class has no member, and member inaccessible
[英]Member is inaccessible. Overloading + Operator
这就是我想要做的。 我正在尝试将f1和f2的每个成员加在一起。 _m是斜率,_b是y间隔。
linear_function operator +
(const linear_function& f1, const linear_function& f2)
{
linear_function f;
f._m = f1._m + f2._m;
f._b = f1._b + f2._b;
return f;
}
但是它说成员无法访问。 这是.h文件。
#ifndef LINEAR_H
#define LINEAR_H
#include <iostream> // Provides ostream
namespace main_savitch_2
{
class linear_function
{
public:
// CONSTRUCTOR
linear_function(double _b = 0.0, double _m = 0.0);
// MODIFICATION MEMBER FUNCTIONS
void set(double _b, double _m);
// CONSTANT MEMBER FUNCTIONS
double eval(double x) const;
double root() const;
double slope() const;
double y_intersept() const;
// CONSTANT OPERATORS
double operator ( ) (double x) const;
private:
double _m, _b;
};
// NON-MEMBER BINARY OPERATORS
linear_function operator +
(const linear_function& f1, const linear_function& f2);
linear_function operator -
(const linear_function& f1, const linear_function& f2);
linear_function operator |
(const linear_function& f1, const linear_function& f2);
// NON-MEMBER OUTPUT FUNCTIONS
std::ostream& operator << (std::ostream& out, const linear_function& p);
}
#endif
我用谷歌搜索成员与非成员运算符的重载,并使我的匹配显示。 不知道为什么我得到这个错误。
由于成员_m
和_b
是私有的,因此仅允许该类的成员及其朋友功能访问它们。 为了使外部函数能够访问成员,您需要在类内部的操作员声明中添加friend
关键字,如下所示:
friend linear_function operator |
(const linear_function& f1, const linear_function& f2);
friend linear_function operator -
(const linear_function& f1, const linear_function& f2);
friend linear_function operator |
(const linear_function& f1, const linear_function& f2);
也许friend
是你的朋友。 尝试将运算符声明为类中的friend
函数,以便提供对类private
成员的访问。
class linear_function
{
....
friend linear_function operator +
(const linear_function& f1, const linear_function& f2);
friend linear_function operator -
(const linear_function& f1, const linear_function& f2);
friend linear_function operator |
(const linear_function& f1, const linear_function& f2);
}
与使用friend
(尤其是如果您仍然想要这些运算符)相比,更好的选择是使用成员分配运算符:
class linear_function
{
// ...
linear_function & operator+= (linear_function const &f)
{
_m += f._m;
_b += f._b;
return *this;
}
};
// non-member but does not need special access rules now
linear_function operator+ (linear_function f1, linear_function const &f2)
{
return f1 += f2;
}
更新:包括成员operator+=
示例实现。 通常,我会内联声明此定义并将其放入.cpp
文件中,但是为了使示例简单.cpp
,此处已.cpp
显示了该定义。
考虑这样的事情:
class linear_function
{
public:
...
linear_function operator+(const linear_function &other) const
{
return linear_function(_b + other._b, _m + other._m);
}
};
如果您无法修改此类的定义,只需保留现有的类外定义,并使用getters linear_function::slope()
和linear_function::y_intercept()
获取_m
和_b
的值:
linear_function operator+(const linear_function &l, const linear_function &r)
{
return linear_function(l.y_intercept() + r.y_intercept(),
l.slope() + r.slope());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.