Solved

how to override operator =

Posted on 1998-07-22
13
232 Views
Last Modified: 2010-04-01
I've written a programm:

class test
{
  private:
    ofstream  osf;
  public:
    test(ofstream& of);
};

test::test(ofstream& of)
{
  osf=of;
  osf<<"text......"<<endl;
}

main()
{
  char  file[256];
  ofstream fout;
  fout.open(file);
  test ts=new test(fout);
  fout.close(file);
}

As I compile the programm, it shows an error message:"Can not generate operator =()". So I add the operator overriding:

class test
{
  private:
    ofstream  osf;
  public:
    test(ofstream& of);
    friend ofstream& operator=(ofstream& s);
};

ofstream& operatoe=(ofstream& s)
{
  return *this;
}

test::test(ofstream& of)
{
  osf=of;
  osf<<"text......"<<endl;
}

main()
{
  char  file[256];
  ofstream fout;
  fout.open(file);
  test ts=new test(fout);
  fout.close(file);
}

I re-compile the programm once again, but this time it shows: "should be 1 parameter for operator". What's wrong?
0
Comment
Question by:chenwei
  • 4
  • 3
  • 3
  • +1
13 Comments
 
LVL 11

Accepted Solution

by:
alexo earned 50 total points
ID: 1168310
Suggestion #1:

>> ofstream& operatoe=(ofstream& s)
                                ^
A spelling mistake?

Suggestion #2:

"Can not generate operator =()" is a very meaningful comment!
The compiler says that (a) operator=() is not defined/accessible for the class and (b) it cannot create a default one.  Why?  Because the programmer of the stream classes explicitly forbid this by declering this operator private or protected.

Lo and behold:

        class fstream : public iostream { /* ... */ };

        class iostream : public istream, public ostream {
        public:
            iostream(streambuf*);
            virtual ~iostream();
        protected:
            iostream();
            iostream(const iostream&);
            inline iostream& operator=(streambuf*);
            inline iostream& operator=(iostream&); // <---- Ooga booga!!!
        private:
            iostream(ios&);
            iostream(istream&);
            iostream(ostream&);
        };



0
 
LVL 8

Expert Comment

by:trestan
ID: 1168311
You do not need to override the = operator. Try the following code. If you are satisfied with it, do not forget to reject the answer so that the person gives you an answer can get the points.
#include<iostream>
#include<fstream>

using namespace std;

class test
{
  private:
    ofstream *osf;
  public:
    test(ofstream& of);
};

test::test(ofstream& of)
{
  osf=&of;
  *osf<<"text......"<<endl;
}

void main()
{
  char  file[256]="test.txt";
  ofstream fout;
  fout.open(file);
  test ts(fout);
  fout.close();
}


0
 

Author Comment

by:chenwei
ID: 1168312
I am very satisfied with trestan's answer.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1168313
Note that trestan's code does not work exactly like your code.  There are subtle, but profound differences.  They may not matter to you, but you should consider them before you employ that solution.  (Its possible also that the differences are even desired--but you have to make that determination.)
0
 
LVL 22

Expert Comment

by:nietod
ID: 1168314
Also not that you said you are satisfied with trestan's answer, but you have accepted alexo's answer.  If you don't like a proposed answer and do like an answer listed in a comment, you must reject the proposed answer and then ask the person who submitted the comment to submit an answer.  Then you can grade that answer.
0
 
LVL 8

Expert Comment

by:trestan
ID: 1168315
But you give your points to another experts. Chenwei, did you notice that?
I found it happens often.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:chenwei
ID: 1168316
First I will like to thank a lot to all sites. No matter how much help I got, you have help me a lot.
Besides, I am not sure why the points I gave trestan is given to another. Perhaps as I wrote the commend and sent it, the other has put his answer.

Thanks a lot again!!!
0
 

Author Comment

by:chenwei
ID: 1168317
By the way, if tretan's code dosen't work exactly like my code, what's your answer, Mr. Nietod?
0
 
LVL 8

Expert Comment

by:trestan
ID: 1168318
When you rate the question, you should notice whoes name is under answer column. And you can correct it if you want. You can either ask Linda to re-assign the point (although it is not prefered)or post another question indicating to whom the points belongs to.

0
 
LVL 22

Expert Comment

by:nietod
ID: 1168319
There is no answer.  As Alexo pointed out what you want were trying to do is explicitly forbidden.  Trestan's approach on the otherhand will compile and will work similarly to what you had in some cases.  However, it will work differently than what you tried is some cases.  That does not mean it is a bad solution.  But you should be aware of the fact that it mayl behave differently than you originally intended.  

for example

ofstream S1);
S1.open(filename.txt"):;
test T1(S1);
{
   ofstream S2);
   S2.open(filename2.txt"):;
   test T2(S2);
   T1 = T2;
   // now T1 and T2 share S2.  That is different behaviour than what you had.
}
 // now S2 is destroyed, but T1 still tries to use it.  This is dangerous.
0
 
LVL 11

Expert Comment

by:alexo
ID: 1168320
There is a very large difference between your original intent and trestan's suggestion.

Orignally, you tried to have a copy of the stream in another, independent, object.  This is explicitly forbidden and probably a bad idea anyway.

trestan suggested having a pointer to the *original* stream object.  Granted, this as a much better idea but you get different behaviour (as nietod pointed out).

It is usually preferred to use a reference instead of a pointer in such cases, but then you must *initialize* (not assign) it in the constructor.  Thus:



    class test
    {
      public:
        test(ofstream& of);
      private:
        ofstream& osf;
    };

    test::test(ofstream& of): osf(of)
    {
      osf << "text......" << endl;
    }

>> You can either ask Linda to re-assign the point (although it is not prefered)
Why not?  Fair is fair.  If you feel trestan gave you a better answer, post a 0-point question in the Expert Exchange Cutomer Support area and tell Linda that the points belong to him.

Don't forget to complain LOUDLY that the current form is non-intuitive, confusing and aggravating.
0
 

Author Comment

by:chenwei
ID: 1168321
Hi, Alexo:

Thanks a lot for your answer!

Besides, I am not sure if Linda is a beautiful girl or not. If yes, I feel shy to critisize her.
0
 
LVL 11

Expert Comment

by:alexo
ID: 1168322
>> Thanks a lot for your answer!
You're welcome!

>> I feel shy to critisize her.
You won't be criticizing her.  She would (hopefully) pass your complaint to the programmers, who would (hopefully) make some changes.  I have it on good authority that the EE programmers are male.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

861 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now