0

当前输出是一个垃圾的 8 位值。我不太清楚为什么加法函数不加 1 和 2。另外,我将如何实现一个函数:

TrashCan other = combined – myCan;
cout << "the other cup's filled to " << other.getUsed( ) << endl;

这是代码:

主要的:

int main()

{
cout << "Welcome to Howie's TrashCan Program!" << endl;

TrashCan myCan;
TrashCan yourCan;

yourCan.setSize( 12 );
myCan.setSize( 12 );

yourCan.addItem( );
yourCan.addItem( );
myCan.addItem( );

myCan.printCan();
yourCan.printCan();

TrashCan combined = yourCan + myCan;
cout << "this drive's filled to " << combined.getUsed( ) << endl;...

班级:

class TrashCan {
public:
TrashCan( );
TrashCan( int size );
TrashCan( int size, int contents );
TrashCan operator+(TrashCan);
TrashCan operator-(TrashCan);
void setSize( int size );
void addItem( );
void empty( );
void cover( );
void uncover( );

void printCan( );
int getUsed();

private:
bool myIsCovered;
int my_Size;
int my_Contents;
};

实现:(我假设我搞砸了以下功能之一)

TrashCan TrashCan::operator+ (TrashCan A)
{
TrashCan combined;
combined.my_Contents= my_Contents + A.my_Contents;
}

int TrashCan::getUsed()
{
return my_Contents;
}
4

2 回答 2

1

您不会在函数中返回临时值:

TrashCan TrashCan::operator+ (TrashCan A)
{
TrashCan combined;
combined.my_Contents= my_Contents + A.my_Contents;
// should be
return combined;
}
于 2013-11-04T03:22:53.037 回答
-1

尝试改变这一点

TrashCan TrashCan::operator+ (TrashCan A)
{
    TrashCan combined;
    combined.my_Contents= my_Contents + A.my_Contents;
}

有了这个

TrashCan TrashCan::operator+ (TrashCan A)
{
    this->my_Contents += A.my_Contents;
    return *this;
}
于 2013-11-04T03:25:21.610 回答