[英]C++ cast operator of pointer
I tried the following code sample but A* aa = c; 我尝试了以下代码示例,但A * aa = c; does not compile.
不编译。 Why is the conversion operator not called?
为什么不调用转换运算符? The same example without pointers works.
没有指针的相同示例有效。 So I do not know why C must inherit from A?
所以我不知道为什么C必须继承自A? Thanks for your help.
谢谢你的帮助。
EDIT: I know coding something like this makes no sense. 编辑:我知道编码这样的事情是没有道理的。 But I just want to understand the conversion stuff.
但我只想了解转换的内容。
#include <iostream>
using namespace std;
class A {
public:
int mValue = 0;
};
class B : public A{
public:
operator A*() {
return this;
}
};
class C {
public:
operator A*() {
return new A();
}
};
int main(int argc, char* argv[])
{
B* b = new B();
A* a = b;
C* c = new C();
A* aa = c;
}
Because expression c
has type C*
, not C
, which is required for the conversion operator to be called. 因为表达式
c
具有类型C*
,而不是C
,所以调用转换操作符是必需的。 C*
and A*
are unrelated types and no conversion exists between them. C*
和A*
是不相关的类型,它们之间不存在转换。
A* aa = *c;
would work. 会工作。
A* a = b;
works because conversion from a pointer to derived class to a pointer to base class is legal and implicit (it doesn't call the conversion operator, mind you). 之所以起作用,是因为从派生类的指针到基类的指针的转换是合法且隐式的(请注意,它不会调用转换运算符)。
The conversion operator is not called, because there is no fitting one . 不会调用转换运算符, 因为没有适合的运算符。
Actually, there cannot be a fitting one, as you are trying to assign from a pointer to one type to a pointer to a different, non-base type. 实际上, 没有合适的方法,因为您试图将一种类型的指针分配给另一种非基本类型的指针。
You can only override operators if you have at least one user-defined type, but the argument is a pointer, and thus not a user-defined-type, and the result (the conversion-operator is the only one where the result is matched) is not either. 仅当您具有至少一个用户定义的类型时才可以覆盖运算符,但是参数是指针,因此不是用户定义的类型,并且是结果(conversion-operator是唯一与结果匹配的变量)也不是。
You need to do the following: 您需要执行以下操作:
A *aa = *c;
which would be equivalent to: 这等效于:
A *aa = c->operator A*();
On the other hand A* a = b;
另一方面,
A* a = b;
is an example of upcasting which happens implicitly in C++ and many other languages. 是向上转换的一个示例,它在C ++和许多其他语言中隐式发生。
Note that you have defined operator for class B and class C and not for pointers to these classes. 请注意,您已经为类B和类C定义了运算符,而不是为这些类的指针定义了运算符。
Check live demo here 在此处查看现场演示
Learnings: There is no implicit conversion to pointers of unrelated types. 经验:没有隐式转换为无关类型的指针。
A pointer can only ever point to objects of its own class, or to objects of a derived type. 指针只能指向其自己的类的对象或指向派生类型的对象。 Since C does not inherit from A, your code will not work.
由于C不继承自A,因此您的代码将无法工作。
I would strongly recommend you have a look at "C++ in 21 days" (search online), the pointer and references section. 我强烈建议您查看“ 21天之内的C ++”(在线搜索),指针和参考部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.