c++ - 显性用户定义的强制转换运算符

标签 c++

假设我有两个类:AB .我定义如何投 ABBA .我还定义了 operator< , operator>operator==对于他们两个,所以我可以比较 AAB到另一个B .然后我创建类 A 的实例,例如a和一类 B , b .我比较它们:

if(a>b){...}

它们中的哪一个会被转换以匹配另一个?除了显式转换之外,还有其他方法可以影响这一点吗?

编辑:我举了一个问题的例子,希望这能帮助解释我自己。 假设我想存储整数。我可以将它们存储在 A 中或在 B .在 A ,我只存储正值。在 B , 只有消极的。完整代码如下。如果a转换为 B , a>b是真的。如果b转换为 A ,这是错误的。试试看。对我来说,如果我不另外投,a>b是假的。我想问的是,是否可以让转换成为主导,以便在这些情况下,我可以确定会发生什么?

啊啊

#ifndef _A
#define _A

class B;

class A{
    private:
        int val;
    public:
        A(int val);
        operator B()const;
        bool operator==(const A& a)const;
        bool operator>(const A& a)const;
        bool operator<(const A& a)const;
};

#endif

B.h

#ifndef _B
#define _B

class A;

class B{
    private:
        int val;
    public:
        B(int val);
        operator A()const;
        bool operator==(const B& b)const;
        bool operator>(const B& b)const;
        bool operator<(const B& b)const;
};

#endif

A.cpp

#include "A.h"
#include "B.h"

A::A(int val){
    this->val=val>=0?val:-val;
}
A::operator B()const{
    return B(-val);
}
bool A::operator==(const A& a)const{
    return val==a.val?true:false;
}
bool A::operator>(const A& a)const{
    return val>a.val?true:false;
}
bool A::operator<(const A& a)const{
    return val<a.val?true:false;
}

B.cpp

#include "A.h"
#include "B.h"

B::B(int val){
    this->val=val>0?-val:val;
}
B::operator A()const{
    return A(-val);
}
bool B::operator==(const B& b)const{
    return val==b.val?true:false;
}
bool B::operator>(const B& b)const{
    return val>b.val?true:false;
}
bool B::operator<(const B& b)const{
    return val<b.val?true:false;
}

主要.cpp

#include <iostream>
using namespace std;

#include "A.h"
#include "B.h"

int main(){
    A a(5);
    B b(-7);
    if(a>b) cout << "a>b is true"   << endl;
    else    cout << "a>b is false"  << endl;
    return 0;
}

编辑:对我来说,它始终是 > 的正确操作数被施放(主要)。此外,如果我将比较运算符声明为友元函数,代码将无法编译,并出现错误 ambiguous overload for 'operator>' in 'b > a'。 ,这是我意料之中的。

最佳答案

operator> 不会投任何东西。它只会将两个操作数与定义的重载进行比较。如果没有这样的重载,您的代码将无法编译。

看起来像这样:

bool operator>(const A& lhs, const B& rhs)
{
   return lhs.foo > rhs.bar; //
}

如果你想在 AB 之间进行转换,你可以在 A 构造函数中使用 B 这样你就可以这样做:

A::A(const B& b) {} //do stuff to convert B to A

A a = someb;

等于 A a(someb);

关于c++ - 显性用户定义的强制转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15325736/

相关文章:

C++ 关于函数模板

c++ - 无法使用 MinGW C++ 在 NetBeans IDE 7.3 中编译 "Hello World"

c# - 适用于 Windows 的 HID 终端

c# - 在 C# 或 C++ 中将压缩的 wav 文件转换为未压缩的 wav 文件的最简单方法是什么?

c++ - 对 vector 中的值求平方

c++ - 映射、类、成员函数

c++ - std::getline() 在使用 cout 时返回内存地址

c++ - 读取表示整数的 6 字节大端二进制字段

c++ - 如何检查 C++ 类中的内存泄漏?

c# - 计算非托管表的填充