【问题标题】:Invalid conversion error? How do i overcome this error?无效转换错误?我如何克服这个错误?
【发布时间】:2021-05-31 15:32:21
【问题描述】:

我想用它们的位置 (0,1,2,3,4) 初始化数组中的 5 个对象。这只是语法错误吗?我觉得我没有正确使用指针。请帮忙!在有人将其标记为重复之前,我知道它与其他几个问题相似,但他们的解决方案似乎都不适合我。除非我做错了,我承认这是可能的,但这就是我在这里的原因。

输出:

代码:

#include <iostream>

using namespace std;

class CuteRobot{
private:
    int position; //x-axis position
    
public:
    CuteRobot(){};
    
    CuteRobot(int p){ //initialize default position
    position = p;
}

    void getPosition(){ //getter
    cout << "position: "<< position;
}

    CuteRobot& move(int steps){ //Positive number for forward motion, negative number for backward motion.  
                                //Ideally, implement function chaining here, CuteRobot&  move(int steps);  
    if(steps >=1){
        position = position + steps;
    } else {
        position = position - steps;
    }
    return *this;
}

    void meet(CuteRobot* cr){ //The function takes a pointer parameter, calculates the steps value when the cr object meets this objectect, 
                              // assuming this object stands still, and use move() function to bring cr object to this object position.
        int steps = (this->position) - (cr->position);
        cr->move(steps);
    }
};

int main()
{
    CuteRobot* cr[5] ={0,1,2,3,4}; // array of five CuteRobot objects.
    
    for(int i =1; i < 5; i++){ //loop through the array and use meet() method to bring every robots to zero position 
                                //(where the first robot stands)?
        cr[i]->meet(cr[0]);
        cr[i]->getPosition();
    }
    return 0;
}

【问题讨论】:

  • 好的,如果我将 CuteRobot* cr[5] ={0,1,2,3,4}; 更改为 CuteRobot* cr{ new CuteRobot[5]{0,1,2,3,4}}; 我不再收到 invalid conversion error 但我确实收到 error: base operand of '- >' 对于cr[i]-&gt;meet(cr[0]);cr[i]-&gt;getPosition(); 具有非指针类型'CuteRobot'

标签: c++ syntax-error


【解决方案1】:

你可能是指它们的数组(不是指向一个的指针):

CuteRobot cr[5] = {0,1,2,3,4};

然后使用对象而不是指针表示法:

 cr[i].meet(cr);
 ...

【讨论】:

  • 但是我得到一个新的错误 错误:没有匹配函数调用'CuteRobot::meet(CuteRobot&)' cr[i].meet(cr[0]); ^
  • 已更新。 cr[0] 是一个对象,但你想要地址。 IE。 &cr[0] 或只是 cr.
  • 如果您愿意,请接受答案并投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 2017-09-12
相关资源
最近更新 更多