这是我的课

#ifndef CARD_H
#define CARD_H

class Card
{
    private:
            int suit, value;
    public:
            Card (int, int);
            int Compare (Card)const;
            void print_card()const;
};

#endif


对于我的比较功能,我想比较两张卡的值,然后进行比较,如果目标卡更大,则返回1,如果我比较的卡更大,则返回0。我该如何完成?

我的Card构造函数应该创建一个新的卡片,但是我不能在构造函数语句中使用“ new”。如果是这种情况,我应该如何创建新卡?

这是我尝试比较的:

int Card::Compare(Card c1) const
{

    if ( c1 == NULL && this == NULL ) return 0;
    else if ( c1 == NULL ) return -1;
    else if ( this == NULL ) return 1;

    else if ( c1.value > this.value ) return 1;
    else if ( c1.value < this.value ) return -1;
    else if ( c1.value == this.value )
    {
        if ( c1.suit > this.suit ) return 1;
        if ( c1.suit < this.suit ) return -1;
    }

最佳答案

在C ++中,this指针是指向该类当前实例的指针。

因为它是一个指针,所以必须将其视为指针:
this->member(*this).member

在C ++中,您只需要使用this指针来避免与方法参数的命名冲突。

我从未使用过this指针,因为我直接引用了成员,并且故意在方法参数和成员变量之间使用不同的名称。

关于c++ - 您如何在C++中的对象中使用“this”指针?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23231603/

10-11 23:01
查看更多