检查调用者和参数是否相同
例如,我有四个类,例如:
class A;
class B{
protected:
void check(const A &a);
};
class C : public A, public B;
class D : public B;
现在我想编写检查函数,如果调用者和参数相同,则该函数不执行任何操作:
void B::check(const A &a){
if(*this != a){
//do something
}
else{
//do nothing
}
}
但是,这不会编译,因为 B 类对 C 类一无所知,有一天它会编译调用 B 的函数检查自身。将 this
转换为 A 会很容易,但是如果有一天 D 类调用该检查,就会出现错误,因为它与 A 无关。那么这样的事情是如何完成的呢?
编辑:我可能不得不提到类 C 和 D 将具有用于调用该检查的接口,该检查在这些类之外不可用,但它除了将参数传递给内部函数之外什么也不做
For example I have four classes like:
class A;
class B{
protected:
void check(const A &a);
};
class C : public A, public B;
class D : public B;
Now I would like to write check function that does nothing if the caller and parameter are the same:
void B::check(const A &a){
if(*this != a){
//do something
}
else{
//do nothing
}
}
However this won't compile as class B doesn't know anything about class C, which will one day call B's function check on itself. It would be easy to cast this
into A, but that would give an error if one day class D would call that check as it has nothing to do with A. How is such thing done then?
Edit: I might had to mention that class C and D will have interface for calling that check which is not avalible outside these classes, but it'll do nothing more than just pass parameter to inner function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您向 A 添加虚拟析构函数,这将起作用:
This would work if you add a virtual destructor to A:
检查是没有意义的,因为 this(B 类) 永远不会与 A 类的类型相同,因为两者都是不相关的类。
目前尚不清楚您想要做什么,但如果您希望基类指针指向派生类对象,那么它们之间必须存在继承(is-a)关系。
Check is meaningless because this(class B) will never be same as type of class A because both are unrelated classes.
It is not clear what you want to do, but if you want your Base class pointer to be pointing to your derived class object then there must be a inheritance(is-a) relationship between them.
这里只有一个可能的逃生口。如果 A 和 B 都具有虚函数,那么您可以对
this
和&a
进行dynamic_cast
。根据 5.2.7/7,“如果 T 是“指向 cv void 的指针”,则结果是指向 v 所指向的最派生对象的指针。”因此,这段代码是有效的:
在不知道该类型的情况下,没有其他方法可以让您获得指向最派生对象的指针。
There's only one possible escape hatch here. If both A and B have a virtual function, then you can
dynamic_cast
boththis
and&a
. And per 5.2.7/7 "If T is “pointer to cv void,” then the result is a pointer to the most derived object pointed to by v."Therefore, this code works:
Nothing else gets you a pointer to the most derived object without knowing that type.
您可能想检查实例是否相同:
比较不同类的内容对我来说没有多大意义。
You probably want to check whether the instances are the same:
Comparing the content of different classes doesn't make much sense to me.
你可以这样做:
You can do something like this:
这就是您要查找的内容吗?检查
this
和a
是否都是C
类型的同一对象的一部分?Is this what you're looking for — to check whether
this
anda
are both parts of the same object of typeC
?