2014-11-05 79 views
1

我有两个文件:没有运营商 “<” 匹配这些操作数的操作数类型是:双<my_class

my_header.h

class my_class { 
public: 
    my_class(); 

    my_class(long long number); 

    my_class(int number); 

    my_class(double number); 

    bool operator<(const my_class& rhs) const; 

    ////// 
} 

my_class.h

my_class::my_class() 
{ 
    //implementation 
} 

my_class::my_class(long long number) 
{ 
    //implementation 
} 

my_class::my_class(int number) 
{ 
    //implementation 
} 

my_class::my_class(double number) 
{ 
    //implementation 
} 

bool my_class::operator<(my_class const& rhs) const 
{ 
    //implementation 
} 

我不明白,我错了。我超载运算符<。另外,我有constructordouble类型。

当然,此外,我执行其他5个运营商(==, !=, >, <=, =>this scheme。其他运算符在同一个命名空间中,但它们不是成员函数。

测试用例

my_class a = 2; 
bool check = 5.17 < long_int1; 
+1

提供一个自由函数'布尔运算符<(双LHS ,my_class const&rhs)'或者从double创建一个临时的'my_class'。 – clcto 2014-11-05 22:30:02

+0

可能重复的[运算符重载:成员函数与非成员函数?](http://stackoverflow.com/questions/4622330/operator-overloading-member-function-vs-non-member-function) – 2014-11-05 22:31:05

+0

clcto,为什么我必须提供这个功能?实际上,我有双重构造函数,为什么C++不会执行double - > my_class? – Denis 2014-11-05 22:31:38

回答

1

C++规则禁止使用隐式转换来创建要在其上调用成员函数的对象 。因此,和 对象支持隐式转换时,通常将二进制 运算符定义为非成员(如果需要,为朋友)。对于 运算符的比较,我有一个简单的模板基类,它将提供它们, 前提是我的类有一个成员函数compare,并从中继承。

template <typename T> 
class ComparisonOperators 
{ 
    friend bool operator==(T const& lhs, T const& rhs) 
    { 
     return lhs.compare(rhs) == 0; 
    } 
    friend bool operator!=(T const& lhs, T const& rhs) 
    { 
     return lhs.compare(rhs) != 0; 
    } 
    friend bool operator<(T const& lhs, T const& rhs) 
    { 
     return lhs.compare(rhs) < 0; 
    } 
    // and so on. 
}; 

你写这一次,然后所有你需要做的就是提供一个(成员) 功能,并从中得出:

class MyClass : public ComparisonOperators<MyClass> 
{ 
public: 
    int compare(MyClass const& other) const 
    { 
     // return <, == or > 0, according to whether this is 
     // <, == or > other. 
    } 
} 
+0

我是对的,在MyClass :: compare函数中,我必须在'(* this)'和'other'之间计算'diff',然后我必须比较'diff'和'0'? – Denis 2014-11-05 23:49:47

+0

@Denis如果'* this'应该在'other'之前排序,等于0'* this'应该被认为是相等的,那么你必须做任何必要的事情来返回一个小于0的int值到'other',如果'* this'应该被认为大于'other',则大于0。这在实践中意味着什么取决于对象中的实际数据类型以及如何定义关系。 – 2014-11-06 09:56:19

+0

感谢您的帮助! – Denis 2014-11-06 11:18:21

0

的问题是,编译器无法知道要隐式转换5.17my_class实例的方式。想想看,如果你有两个不同的类可以接受double作为唯一的构造函数参数,会发生什么。有两种解决方法。

  1. 提供转换运算符。这将允许编译器将my_class的实例作为double读取。
  2. 切换参数的顺序。 !(my_class > 5.17)应该可以正常工作。
+0

我做了什么,如果my_class不能转换为double,并且我不能切换参数的顺序? – Denis 2014-11-05 23:10:20

+0

如果你做了一个比较,那么比较必须为你的课程计算一个“价值”,并将其与5.17进行比较。这个“值”可以由转换操作符返回。你怎样才能不改变参数?只是代码可读性? – 2014-11-05 23:13:58

+0

我的对象可以更多,然后MAX_DOUBLE。我不切换参数,因为此代码是由外部系统测试的。 – Denis 2014-11-05 23:16:04

相关问题