如何解决多次继承的不明确变量名称?
How to resolve ambiguous variables names inherited multiple times?
所以我有以下问题。我有一个 class,它是另外两个 classes 的子 class,它们都有位置。就像这个例子:
struct A
{
float x, y;
std::string name;
void move(float x, float y)
{
this->x += x;
this->y += y;
}
};
struct B
{
float x, y;
int rows, columns;
void move(float x, float y)
{
this->x += x;
this->y += y;
}
};
struct C : public A, public B
{
void move(float x, float y)
{
this->x += x; //generates error: "C::x is ambiguous
this->y += y; //generates error: "C::y is ambiguous
}
};
稍后在代码中我将 class C 称为 A class 和 B class,当我得到位置时我遇到了问题。我能以某种方式 "combine" 定位两个 classes 的变量吗?如果不能,我可以同时更改两个 classes 的位置,还是我必须这样做:
void move(float x, float y)
{
this->x1 += x;
this->y2 += y;
this->x1 += x;
this->y2 += y;
}
提前致谢!
在 C++ 中,这可以通过在成员变量前加上其 class 作用域来消除歧义:
struct C : public A, public B
{
void move(float x, float y)
{
A::x += x;
A::y += y;
B::x += x;
B::y += y;
}
};
所以我有以下问题。我有一个 class,它是另外两个 classes 的子 class,它们都有位置。就像这个例子:
struct A
{
float x, y;
std::string name;
void move(float x, float y)
{
this->x += x;
this->y += y;
}
};
struct B
{
float x, y;
int rows, columns;
void move(float x, float y)
{
this->x += x;
this->y += y;
}
};
struct C : public A, public B
{
void move(float x, float y)
{
this->x += x; //generates error: "C::x is ambiguous
this->y += y; //generates error: "C::y is ambiguous
}
};
稍后在代码中我将 class C 称为 A class 和 B class,当我得到位置时我遇到了问题。我能以某种方式 "combine" 定位两个 classes 的变量吗?如果不能,我可以同时更改两个 classes 的位置,还是我必须这样做:
void move(float x, float y)
{
this->x1 += x;
this->y2 += y;
this->x1 += x;
this->y2 += y;
}
提前致谢!
在 C++ 中,这可以通过在成员变量前加上其 class 作用域来消除歧义:
struct C : public A, public B
{
void move(float x, float y)
{
A::x += x;
A::y += y;
B::x += x;
B::y += y;
}
};