C ++对象和C风格的问题 [英] C++ object and C style cast question
问题描述
我有以下代码由gcc编译:
I have the following code compiled by gcc:
#include <iostream>
using namespace std;
class Buffer {
public:
operator char *() { cout << "operator const * called" << endl; return buff; }
private:
char buff[1024];
};
int main(int, char**) {
Buffer b;
(char *)b; // Buffer::operator char * is called here
return 0;
}
我看到的是Buffer :: operator char *
What I see is that Buffer::operator char * is called on line:
(char *)b;
为什么C风格的转型调用Buffer :: operator char *
Why C style cast calls Buffer::operator char * is called here?
我认为
static_cast<char *>(b);
来显式调用Buffer :: operator char *。
should be used in order to invoke explicitly Buffer::operator char *.
推荐答案
如果你做了(char *)(& b)
样式转换和 operator char *
将不会被调用。这里你试图将一个对象转换为char *。由于没有自动转换编译器查找由您提供的operator char *。如果你没有提供它,你将得到一个编译器错误,说 Buffer
不能转换为 char *
If you had done (char *)(&b)
it would have been C style cast and operator char*
will not be called. Here you are trying to cast an object into char*. Since there is no automatic conversion compiler looks for operator char* provided by you. If you had not provided it, you'll get a compiler error saying that Buffer
can not be converted into char*
这篇关于C ++对象和C风格的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!