假设我有两个类:A
和 B
.我定义如何投 A
至 B
和 B
至 A
.我还定义了 operator<
, operator>
和 operator==
对于他们两个,所以我可以比较 A
到A
或 B
到另一个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; //
}
如果你想在 A
和 B
之间进行转换,你可以在 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/