use*_*241 11 c++ operator-overloading
如果我需要在派生类中使用它们,我是否必须重新定义所有带派生类型的重载运算符?
以下代码编译正常:
class Point {
public:
Point(int X = 0, int Y = 0):x(X), y(Y) {}
virtual ~Point() {}
Point operator +(Point &rhs) {
return Point(x + rhs.x, y + rhs.y);
}
protected:
int x, y;
};
class Vector : public Point {
public:
Vector(int X, int Y) : Point(X, Y) {}
~Vector() {}
Vector operator +(Vector &rhs) {
return Vector(x + rhs.x, y + rhs.y);
}
};
int main()
{
Vector v1(1, 2);
Vector v2(3, 2);
Vector v3 = v2 + v1;
}
Run Code Online (Sandbox Code Playgroud)
但是从我读过的,
C++ Primer 4th Ed.第15.5.3节.
如果派生类想要通过其类型使所有重载版本可用,那么它必须重新定义所有这些版本或不重新定义它们.
引用" none of them" 部分在这里有意义吗?
小智 6
无论返回类型或参数如何,类A中名为f的成员函数都将隐藏A基类中名为f的所有其他成员.以下示例演示了这一点:
struct A {
void f() { }
};
struct B : A {
void f(int) { }
};
int main() {
B obj_B;
obj_B.f(3);
// obj_B.f();
}
Run Code Online (Sandbox Code Playgroud)
编译器不允许函数调用obj_B.f(),因为void B :: f(int)的声明隐藏了A :: f().
要在派生类B中重载而不是隐藏基类A的函数,可以使用using声明将函数的名称引入B的范围.除了使用A :: f的using声明之外,以下示例与前一个示例相同:
struct A {
void f() { }
};
struct B : A {
using A::f;
void f(int) { }
};
int main() {
B obj_B;
obj_B.f(3);
obj_B.f();
}
Run Code Online (Sandbox Code Playgroud)
因此,如果不重载所有这些,则只使用重载函数.
这意味着如果Point有多个operator+(),并且你只重新定义了其中一个,那么只有那个可以在派生类中访问; 其他重载将被隐藏.如果在派生类中声明为no operator+(),那么所有父类都可用; 如果你声明任何在派生类中,则没有家长的人都可用.
合理?这种情况很好:父母声明一个,然后重新定义那个.没问题.但是,如果父级声明了两个,那么您的子类(仅声明一个)只能访问该子类.