at school,I was given the class aName and asked to overload the input operator.the class has declared surname as type of char* and the surname is input from the keyboard and it must not be empty.please help me with the code.the class has declared the operator as its friend

Recommended Answers

All 6 Replies

post the class then we can discuss how to implement to >> operator.

post the class then we can discuss how to implement to >> operator.

class aName
{
friend std::istream operator>>(std::istream & input,aName &name);
/*input the name from the standard input stream like the keyboard and the name is never empty*/
friend std::ostream operator<<(std::ostream & output,aName name);
//it displays the name on the standard output like the screen

private:
char*surname,
       *firstname;

public:aName(char *aSurname,char*aFirstname);
void set(char *aSurname,char* afirstname)
{
if(aSurname=="")
  surname="";
else
surname=aSurname;
if(afirstname=="")
firstname="";
else
firstname=afirstname;
};
Member Avatar for jencas

Warning! This line

surname=aSurname;

just copies the pointer not the content!!!

>>surname=aSurname;

First you have to allocate space for surname then call strcpy() to copy it

surname = new char[strlen(aSurname)+1];
strcpy(surname, aSurname);

The two friend functions must return a reference to the istream and ostream objects. Here's correction

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
#pragma warning( disable: 4996) // only needed for VC++ 2008 compiler

class aName
{
friend std::istream& operator>>(std::istream & input,aName &name);
/*input the name from the standard input stream like the keyboard and the name is never empty*/
friend std::ostream& operator<<(std::ostream & output,aName name);
//it displays the name on the standard output like the screen

private:
char*surname,
    *firstname;

public:
    aName() { surname = NULL; firstname = NULL;}
    aName(char *aSurname,char*aFirstname)
    {
        surname = NULL; firstname = NULL;
        set(aSurname, aFirstname);
    }

    void set(char** name, const char* aName)
    {
        if( *name != NULL)
            delete[] *name;
        *name = NULL;
        if( aName != NULL)
        {
            *name = new char[strlen(aName)+1];
            strcpy(*name, aName);
        }
    }
    void set(const char *aSurname,const char* afirstname)
    {
        set(&surname, aSurname);
        set(&firstname, afirstname);
    }
};

istream& operator>>(istream& in, aName& nm)
{
    // TODO:  complete this function.
    return in;
}

int main()
{
    aName n;
    cin >> n;
}

[edit]Oops! I just noticed I did half your homework:(

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.