问题描述
如果我需要在派生类中使用它们,我必须重新定义所有带有派生类型的重载操作符吗?
下面的代码编译得很好:
class Point {
public:
Point(int X = 0,int Y = 0):x(X),y(Y){}
virtual〜Point(){}
点算符+ $ b 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& rhs){
return Vector(x + rhs.x,y + rhs.y) ;
}
};
int main()
{
Vector v1(1,2);
Vector v2(3,2);
Vector v3 = v2 + v1;
}
但根据我所阅读的内容,
C ++ Primer 4th Ed。 Section 15.5.3。
引用部分其中没有
在这里有什么意义吗?
有多个运算符+()
,你只重定义其中一个,那么只有那个可以在派生类中访问;其他重载将被隐藏。如果在派生类中声明了 no operator +()
,那么所有的父类都可用;如果您在衍生类中声明了任何,则父类的 none 可用。
有意义吗?这种情况很好:父声明一个,你重新定义一个。没问题。如果父类声明了两个,那么你的子类只能声明一个,只能访问那个。
Must I need to redefine all the overloading operators with derived type if I require to use them in derived class?
The following code compiles fine:
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;
}
But from what I've read,
C++ Primer 4th Ed. Section 15.5.3.
Does the part of quote "none of them
" make any sense here?
解决方案 What it means is that if Point
had more than one operator+()
, and you only redefined one of them, then only that one would be accessible in the derived class; the other overloads would be hidden. If you declare no operator+()
in the derived class, then all of the parent ones are available; if you declare any in the derived class, then none of the parent ones are available.
Make sense? This case is fine: the parent declares one, and you redefine that one. No problems. If the parent declared two, though, then your child class, which only declares one, would only have access to that one.
这篇关于在派生类中重载运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!