在C ++中将对象添加到数组

时间:2014-03-24 04:24:30

标签: c++

在header.h中

上课前:课程Treadmill;

私人:Treadmill* treadmillList;

public:bool addTreadmill(Treadmill * Obj);

在header.cpp中

Constructor: treadmillList = new Treadmill[LISTSIZE];

bool Trainee::addTreadmill(Treadmill *Obj) {
    treadmillList[numOfTreadmills++]=Obj;
}

编译结果:

treadmill.cpp: In member function ‘bool Trainee::addTreadmill(Treadmill*)’:
treadmill.cpp:39:34: error: no match for ‘operator=’ (operand types are ‘Treadmill’ and ‘Treadmill*’)
  treadmillList[numOfTreadmills++]=Obj;
                                  ^
treadmill.cpp:39:34: note: candidate is:
In file included from treadmill.cpp:3:0:
treadmill.h:3:7: note: Treadmill& Treadmill::operator=(const Treadmill&)
 class Treadmill {
       ^
treadmill.h:3:7: note:   no known conversion for argument 1 from ‘Treadmill*’ to ‘const Treadmill&’

2 个答案:

答案 0 :(得分:1)

只要查看您发布的代码,我认为您尝试将Treadmill指针或地址存储到Treadmill中的Treadmill对象中。如果你想存储指针以在数组中键入Treadmill,请尝试:

Treadmill** treadmillList;
Constructor: treadmillList = new Treadmill*[LISTSIZE];

这只是基于我观察到的情况,虽然你没有说明你的目标是什么以及你的问题究竟是什么。

答案 1 :(得分:0)

请尝试此代码

bool Trainee::addTreadmill(Treadmill *Obj) {
    treadmillList[numOfTreadmills++] = *Obj;
}