Error C3440 on overloaded operator []

D

Dan

Hi. I'm fairly new to C++, and am getting an error when trying to
overload the [] operator.

Here's an example of the problem ...


class CMyClass
{
};

class CMyClassCollection
{
public:
CMyClass* operator [] (unsigned int index) const
{
return my_list [index];
}

private:
vector <CMyClass *> my_list;
};

void CMyCodeClass::do_stuff ()
{
CMyClassCollection my_collection;

... initialise my_collection here

CMyClass *my_class = my_collection [0];
}


The last line of the do_stuff function gives me this compiler error
message ...

error C2440: 'initializing' : cannot convert from 'CMyClass *' to
'CMyCodeClass::CMyClass *'
Types pointed to are unrelated; conversion requires reinterpret_cast,
C-style cast or function-style cast


Any ideas what this means?

Thanks for any help,
- Dan
 
T

Tomás

Dan posted:
Hi. I'm fairly new to C++, and am getting an error when trying to
overload the [] operator.


The following code compiles without error or warning for me:

#include <vector>
using std::vector;

class CMyClass
{
};

class CMyClassCollection
{
public:
CMyClass* operator [] (unsigned int index) const
{
return my_list [index];
}

private:
vector <CMyClass *> my_list;
};

struct CMyCodeClass {
void do_stuff();
};

void CMyCodeClass::do_stuff ()
{
CMyClassCollection my_collection;

//... initialise my_collection here

CMyClass *my_class = my_collection [0];
}

int main() {}


-Tomás
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top