Pergunta

I'm trying allow for method chaining on the Constructor and I have ran into the same problem on this C++ method chaining including class constructor and I have tried the suggested answers but still getting the same error. My code is below:

class Signal {

public:
    Signal() { }

    Signal& Emphasize() {

        return *this;
    }   

};
enum ReadType { NATIVE = 0, DOUBLE, };

class Wav : public Signal {

  public:

          Wav(string fileName, ReadType type) {

    }   

};

I have tried calling from the following:

Wav* wave = new Wav("asf", DOUBLE).Emphasize();

And:

Wav wave = Wav("asf", DOUBLE).Emphasize();

I don't know whether the actual process is possible since "Emphasize" it's not a constructor but hopefully I will be allowed to access it. What could I be doing wrong here for this not to work?

Hope someone can help :)

UPDATE:

I put "Emphasize()" as a class member inside "Wav" and it worked, how I wanted. BUT does anyone know of a way I can access this member inside "Signal" without having to place the class member inside of "Wav"?

UPDATE:

class Signal {

public:
    Signal() { }

    Signal* Emphasize() {
        return this;
    }
 };
 enum ReadType {

        NATIVE = 0, DOUBLE,
    };

 class Wav : public Signal {

   public:
      Wav(string fileName, ReadType type) {

       }    
 };

 int main(int argc, char *argv[]) {

  Wav* wave = new Wav("asf", DOUBLE)->Emphasize();
 }
Foi útil?

Solução

The new expression returns a pointer so you just have to do :

Wav* wave = new Wav("asf", DOUBLE)->Emphasize();
//                                ^^

Also your method Emphasize return a reference on a Signal object :

Signal& Emphasize() {
//    ^ Reference
    return *this;
}

But you are trying to assign this reference to a pointer Wav*.

You have two choices here :

// ...
Signal* Emphasize() {
    return this;
}

// ...
Wav* wave = new Wav("asf", DOUBLE)->Emphasize();

Or you keep you initiale Emphasize method :

// ...
Signal& Emphasize() {
    return *this;
}

// ...
Wav wave = new Wav("asf", DOUBLE)->Emphasize();

EDIT : Ok the real error is that you are trying to convert a Signal object into Wav object.

There is no convertion from Signal to Wav object.

A Wav is a Signal but a Signal is not a Wav.

You can do something like :

Inside your Signal class :

virtual Signal& Emphasize()=0;

And inside your Wav class :

Wav& Emphasize()
{
     return *this;
}

OR

Signal w = new Wav( "asf", DOUBLE )->Emphasize();

Outras dicas

Are you looking for something like this?

Wav* wave = new Wav("asf", DOUBLE);
Signal x = wave->Emphasize();

Or if you want Wav object at the end, you can define Emphasize() virtually at Signal class

virtual Signal& Emphasize()=0;   

Then at Wav class you can define

Wav& Emphasize(){

    return *this;
}

In the main you can call

Wav* wave = new Wav("asf", DOUBLE);
Wav w = wave->Emphasize();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top