0

我遇到错误读取,从“int”转换为“TrashCan”的功能样式没有匹配的转换。

这是标题中的声明:

class TrashCan
{
friend TrashCan operator +( TrashCan& left,
                          TrashCan& right);
public:
TrashCan();
int size=0;
int item=0;

void setSize(int);
void addItem();

这是我的实现:

TrashCan operator +(const TrashCan& left,
              const TrashCan& right) {
TrashCan t= TrashCan( left.size + right.size );
return( t );

}

这是底部带有运算符的主要内容:

int main( ) {

cout << "Welcome to My 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;
4

1 回答 1

3

编辑

你像这样声明你的构造函数:TrashCan();

但是你这样称呼它:TrashCan t= TrashCan( left.size + right.size );.

您需要有第二个构造函数,例如TrashCan(int nsize) : size(nsize) { }.

godel9 已经在评论中给出了答案,但这里有一个工作代码示例:

#include <iostream>

class TrashCan {
    // Your declaration did not match your definition
    // Need to put const here
    friend TrashCan operator +(const TrashCan& left,
                          const TrashCan& right);
    public:
        TrashCan(int nsize) : size(nsize) { }
        ~TrashCan() { }
        int size;                      
};

TrashCan operator +(const TrashCan& left,
              const TrashCan& right) 
{
    TrashCan t= TrashCan( left.size + right.size );
    return( t );
}

int main()
{
    TrashCan tc1(10);
    TrashCan tc2(20);

    std::cout << (tc1 + tc2).size;
    // outputs 30
    return 0;
}
于 2013-11-04T00:13:59.870 回答