0

I need some help.

this is my function:

 class teacher
{
    public:
    char  &operator[](int i);
    protected:
    char* contents;
};

.cpp

    char & teacher::operator[](int i) 
{
    return contents[i];
}

main

    teacher s1;
cout<<"Enter names: "<<endl;
cin>>s1[1];
cout<<s1[1];

If I enter a word, it only returns the first character, I don't know why if I'm using a char*

  • Too many problems. [This](http://stackoverflow.com/q/388242/1870232) always helps – P0W Nov 24 '13 at 19:55

3 Answers3

0

If you want an array of char* you need to make it a char**. contents[i] is a char, not a char*.

Why not use a vector<string> ?

Charlie
  • 1,487
  • 10
  • 9
  • I tryed making it a char **; but it gives me an error: C2440: saying something like I can't convert 'char *' to 'char &'. And about using a vectror I don't know how to use it – user3025483 Nov 24 '13 at 20:04
0

You use a char*, but your operator [] returns a char&, which is not the same as a char*.

If you modify the char& you modify only one character.

xorguy
  • 2,594
  • 1
  • 16
  • 14
0

What you want to be doing is this:

class teacher {
    public:
        char*& operator[](int i);
    protected:
        char** contents;
};

char*& teacher::operator[](int i) {
    return contents[i];
}

Here you have an array of char*, i. e. C-style strings. The [] operator returns one of these char* as a reference, so that the code can change the pointer to point to some other string. This is according to the common C++ accessor idiom.

If you would choose to use std::string, you would just need to replace all occurences of char* with std::string.


Personally, however, I don't say that this approach is necessarily the best one; I have some objections against interfaces that expose the inner workings of a class like this. In this case any caller can obtain a reference to a pointer used by the class, and can use it at any later time to directly modify the contents of teacher without going through another teacher method. This makes it impossible to ensure any consistency of contents with the value of any other data member of teacher.

I try to avoid accessors in code I write, and favour methods that actually do something. That helps avoid code clutter and allows method names to name higher level operations. But that is just my opinion, many other people see it very differently.

cmaster - reinstate monica
  • 38,891
  • 9
  • 62
  • 106