Referencing to a pointer member in a different cla

2019-09-26 07:20发布

I have a Note and a Track class which both *generator member. When I create new Note objects I want to link the generator member of Note to that of Track but I can't figure out how to do this.

#include <iostream>
using namespace std;

class Generator {
public:
    virtual float getSample(int sample)=0;
};

class Note {
public:

    Generator *generator; // THIS IS WHAT IS CAUSING ME TROUBLE
    Note(Generator *aGen){
        generator = aGen;
    }
};

class Synth  : public Generator{
public:
    virtual float getSample(int sample);
    int varA;
    int varB;
    Synth(){
        varA = 5;
        varB = 8;
    }
};


float Synth::getSample(int sample){
    varA = sample;
    varB = 3;

    return 0;
}

class Track {
public:
    Generator *generator;
    Track(){
        generator = new Synth();
    }
};

int main() {
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    Track track = Track();
    cout << "test" << endl;
    return 0;
}

I thought of doing something like this, but it's not working:

Track track = Track();
Note n = Note(&track.generator);

Error

prog.cpp: In function ‘int main()’: 
prog.cpp:48:35: error: no matching function for call to ‘Note::Note(Generator**)’ 
prog.cpp:48:35: note: candidates are: 
prog.cpp:13:5: note: Note::Note(Generator*) 
prog.cpp:13:5: note: no known conversion for argument 1 from ‘Generator**’ to ‘Generator*’ prog.cpp:9:7: note: Note::Note(const Note&) 
prog.cpp:9:7: note: no known conversion for argument 1 from ‘Generator**’ to ‘const Note&’ prog.cpp:48:10: warning: unused variable ‘n’ [-Wunused-variable] - See more at: http://ideone.com/E38ibe#sthash.V3QMcYJQ.dpuf

Live example here.

2条回答
Bombasti
2楼-- · 2019-09-26 07:44

track.generator is a pointer to Generator already, you don't need to take its address.

Just stay with

Node n = Node(track.generator); // without & operator

Updated code: http://ideone.com/fAA4JX

查看更多
对你真心纯属浪费
3楼-- · 2019-09-26 07:58

As the compiler is telling you, this line:

Note n = Note(&track.generator);

Tries to construct a Note and supply a Generator** to its constructor (since track.generator has type Generator*, &track.generator has type Generator**).

However, your Note class constructor accepts a Generator*, not a Generator**. Just do this instead (notice, that copy-initialization is unnecessary here, rather use direct-initialization):

Track track;
Note n(track.generator);
查看更多
登录 后发表回答