C++ C++;:为什么在进行测试之前转换为void*

C++ C++;:为什么在进行测试之前转换为void*,c++,pointers,C++,Pointers,有人知道为什么这两个指针this和&op2在比较之前首先转换为void*?(这个例子取自C++模板:David Vandevoorde和Nicolai M. Josuttis的完全指南)< /P> 模板 模板 堆栈和运算符=(常量堆栈和op2){ if((void*)this==(void*)&op2){ 归还*这个; } // .... } 正如@KerrekSB在评论中提到的,这是一种糟糕的编码风格 作者试图避免在比较不同类型的指针时出现编译时警告,例如Stack*类型的指针和Stack*类

有人知道为什么这两个指针
this
&op2
在比较之前首先转换为
void*
?(这个例子取自C++模板:David Vandevoorde和Nicolai M. Josuttis的完全指南)< /P>
模板
模板
堆栈和运算符=(常量堆栈和op2){
if((void*)this==(void*)&op2){
归还*这个;
}
// ....
}

正如@KerrekSB在评论中提到的,这是一种糟糕的编码风格

作者试图避免在比较不同类型的指针时出现编译时警告,例如
Stack*
类型的指针和
Stack*
类型的指针

通过使用重载可以很容易地避免这种情况

// Assign an object of the same type.
template<typename T>
Stack<T>& operator=(const Stack<T> & op2){
    if (this == &op2){
        return *this;
    }
    // ....
}

// Assign an object of a different type.
template<typename T>
template<typename T2>
Stack<T>& operator=(const Stack<T2> & op2){

    // For objects of different types, this check is not necessary
    // at all. It will always be false.
    // if ((void*)this==(void*)&op2){
    //     return *this;
    /// }

    // ....
}
//指定相同类型的对象。
模板
堆栈和运算符=(常量堆栈和op2){
if(this==&op2){
归还*这个;
}
// ....
}
//指定不同类型的对象。
模板
模板
堆栈和运算符=(常量堆栈和op2){
//对于不同类型的对象,不需要进行此检查
//一点也不,它永远都是假的。
//if((void*)this==(void*)&op2){
//归还*这个;
/// }
// ....
}

因为两个不同类型的指针不可比较?(但这意味着测试很愚蠢。应该有两个重载,一个用于带测试的同质类型,一个用于不带测试的混合类型。)有人能帮我读一下吗?这是一个允许将堆栈分配给堆栈的操作符,所以我可以将堆栈分配给堆栈?检查堆栈是否已经是相同的堆栈?@MobyDisk,这是一种可能性,前提是可以将
分配给
。它适用于可以隐式转换的类型。例如,您将能够将
堆栈
分配给
堆栈
@RSahu,您确定吗?我们对这个堆栈类了解不多,但是STL容器不支持您所描述的内容。对于C,我发现它支持更多:标准不需要两个指向不同对象类型的指针来进行比较。见第5-6页。这也是适用于C++的,即>因为操作数不需要引用相同的对象,所以需要比较在指针值中表示的所有信息>(例如分段架构中的段和偏移)。[...]
// Assign an object of the same type.
template<typename T>
Stack<T>& operator=(const Stack<T> & op2){
    if (this == &op2){
        return *this;
    }
    // ....
}

// Assign an object of a different type.
template<typename T>
template<typename T2>
Stack<T>& operator=(const Stack<T2> & op2){

    // For objects of different types, this check is not necessary
    // at all. It will always be false.
    // if ((void*)this==(void*)&op2){
    //     return *this;
    /// }

    // ....
}