我一直在读一本计算几何学的书。在这样的书中有一个介绍部分,其中介绍了如何实现基本的 Vertex 数据结构。本书遵循的路线如下。
首先说明了如何实现一个List数据结构,具体节点接口(interface)如下
class Node {
public:
Node();
Node* getNext();
Node* getPrev();
void setNext(Node *x);
void setPrev(Node *x);
Node* insert(Node *x);
Node* remove();
void splice(Node *x);
private:
Node *next;
Node *prev;
};
然后实现了一个Point类,接口(interface)如下
class Point2D {
public:
Point2D();
Point2D(double x, double y);
Point2D(const Point2D& p);
void setX(double x);
void setY(double y);
double getX();
double getX() const;
double getY();
double getY() const;
Point2D operator+(Point2D& p);
Point2D operator-(Point2D& q);
Point2D operator-();
Point2D& operator=(const Point2D& p);
bool operator==(Point2D& p);
bool operator!=(Point2D& p);
bool operator>(Point2D &p);
bool operator>=(Point2D &p);
bool operator<(Point2D &p);
bool operator<=(Point2D &p);
friend Point2D operator*(double c, Point2D p);
double getDistance(Point2D& q);
double getLength();
int orientation(Point2D p, Point2D q);
int classify(Point2D p, Point2D q);
private:
double x;
double y;
};
最后我们有了顶点类
class Vertex : public Node, public Point2D {
public:
Vertex(double x, double y);
Vertex(Point2D x);
Vertex *cw();
Vertex *ccw();
Vertex *neighbour(int direction);
Point2D getPoint();
Vertex *insert(Vertex *v);
Vertex *remove(Vertex *v);
void splice(Vertex *v);
friend class Polygon;
};
让我们具体来说一下方法
Point2D Vertex::getPoint() {
return *((Point2D*)this);
}
Vertex *Vertex::insert(Vertex *v) {
return (Vertex*)(Node::insert(v));
}
如您所见,其中涉及一些转换。现在,如果我有单一继承,我知道所有数据成员都会像“堆叠”一样,并且转换将包括计算基类给定的基地址的偏移量。
喜欢:
class A {
public: int a;
};
class B : public A {
public: int b;
};
在某处
B b;
A a = *(A*)&b;
在这种情况下,我会说,b
有一个基地址(让我们将这样的地址命名为 b_addr
,转换为 A(实际上不是转换,但无论如何...也许你明白我的意思)会涉及“考虑”从 b_addr
到 b_addr + 4
。但是我不确定这个计算是如何工作的在多重继承的情况下。谁能给我解释一下?
最佳答案
在单继承的情况下:
struct A { int a; };
struct B : A { int b; };
struct C : B { int c; };
C c;
这里c
、(B&)c
和(A&)c
地址相同;从一个结构转换为层次结构的任何其他结构时,没有添加或减去偏移量。
在多重继承的情况下:
struct A { int a; };
struct B { int b; };
struct C : A,B { int c; };
C c;
这里c
和(A&)c
有相同的地址,但是(B&)c
的地址偏移了sizeof (A)
来自 c
的地址。此外,(char*)&c.c == (char*)&c + sizeof(A) + sizeof(B)
。
关于c++ - 多重继承 C++,转换是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40319355/