Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

how to override operator =

Posted on 1998-07-22
13
234 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
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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
 

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Unable to start eclipse ? 17 154
Installshield for Embarcadero EX 10.1 Berlin 4 60
Error creating a new C++ project in ,net 20 41
No module found pypyodbc, 3 33
When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

837 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