我遇到错误阅读,没有从'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;

最佳答案

编辑

您可以这样声明构造函数: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;
}

关于c++ - C++运算符重载错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19759748/

10-10 19:50