home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!taumet!steve
- From: steve@taumet.com (Steve Clamage)
- Subject: Re: Friend ..Overload Assignment opertr ..
- Message-ID: <1993Jan23.200432.16195@taumet.com>
- Organization: TauMetric Corporation
- References: <1993Jan22.075317.21062@usl.edu>
- Date: Sat, 23 Jan 1993 20:04:32 GMT
- Lines: 42
-
- rks9954@usl.edu (Srinivasa Rao K) writes:
-
-
- > I am writing a "string" class which i should be able to use like
-
- > string str1;
- > str1 = "Hello world" ;
-
- > But We canot use a friend to overload the assignment oprator.
-
- A String class will usually contain pointers, and so should have
- a user-defined assignment operator (which must be a member function,
- as you note) and copy constructor. If not, you will be vary likely to
- have bizarre program crashes. See the book "Effective C++" by Scott
- Meyers for a detailed discussion.
-
- If you add a String constructor which takes a const char* parameter,
- you don't have to do anything else. It is hard to imagine a String
- class without such a constructor. Example:
-
- class String {
- public:
- String(); // default constructor (optional)
- String(const char*);
- String(const String&); // copy constructor
- String& operator=(const String &); // assignment operator
- ...
- };
-
- String s;
- s = "Hello";
-
- The string "Hello" will automatically be converted to a String by the
- constructor, then assigned via the assigment operator. The code is
- evaluated as if you had written
- s.operator=( String("Hello") );
-
- The copy constructor is not relevent for this example, but you should
- have one anyway.
- --
-
- Steve Clamage, TauMetric Corp, steve@taumet.com
-