运算符< =重载2个类并转换ctor

时间:2016-01-11 08:53:56

标签: c++ constructor operator-overloading

我有一个小问题,Visual Studio编译器似乎并没有受到困扰,但是在eclipse和g ++中都有。

我有2个班,Card和CardDeck。我确实有运算符< = for 2 Carddecks作为参数,而不是2卡。我有一个转换ctor,它将卡转换为甲板。

所以当我这样做时问题是:

<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
    <item name="android:headerBackground">@color/chosen_header_bg_color</item>
</style>

在视觉上可以正常工作,因为它将左侧部分转换为卡座,然后转换为右侧,然后进行比较。

在g ++中它说:

card1 <= card2

但不应该是一个人。正如我所说,我希望转换ctor会传达双方并进行比较?

对此有何解释和解决方案?

编辑(运营商和ctor声明和代码):

no match for 'operator<=' (operand types are 'Card' and 'Card')

2 个答案:

答案 0 :(得分:0)

Deck(card1) <= Deck(card2)

使operator<= (operand types are 'Card' and 'Card')覆盖,因为您在card1 <= card2表达式中使用(均值)。您的代码存在架构错误。

<强>更新

struct Card
{
    bool operator<( const Card& right ) const;
};

struct Deck
{
    std::vector<Card> m_arr;

    Deck() = default;
    Deck( const Card& conversion )
    {
        m_arr.push_back( conversion );
    }
    bool operator<( const Deck& right ) const;
};

bool Card::operator<( const Card& right ) const
{
    return false;
}
bool Deck::operator<( const Deck& right ) const
{
    bool result = false;
    if(m_arr.size() < right.m_arr.size())
    {
        result = true;
    }
    else if(!m_arr.empty() && m_arr.size() == right.m_arr.size() )
    {
        result = true;
        std::vector<Card>::const_iterator it = right.m_arr.begin();
        std::vector<Card>::const_iterator it2 = m_arr.begin();
        for(; it2 != m_arr.end(); ++it, ++it2 )
        {
            if((*it) < (*it2))
            {
                result = false;
                break;
            }
        }
    }    
    return result;
}

答案 1 :(得分:0)

这是我认为你想要做的快速和肮脏的事情:

#include <iostream>

struct Element
{
    int x;
    Element() :x(0) {}
    virtual ~Element() {}
};

struct Container
{
    Element elems[10];
    int n;
    Container() { n=0; }
    Container(const Element &e) { elems[0]=e; n=1; }
    virtual ~Container() {}
    friend bool operator<=(const Container &l, const Container &r);
};

bool operator<=(const Container &l, const Container &r)
{
    if (l.n<=r.n) { std::cout << "less/equ\n"; return true; }
    else { std::cout << "greater\n"; return false; }
}

int main(int argc, const char *argv[])
{
    //Container container;
    Element a, b;
    if (a<=b) std::cout << "okay\n"; else std::cout << "fail\n";
    return 0;
}

它适用于gcc。