【问题标题】:Referencing to a pointer member in a different class引用不同类中的指针成员
【发布时间】:2013-03-03 13:23:16
【问题描述】:

我有一个Note 和一个Track 类,它们都是*generator 成员。当我创建新的Note 对象时,我想将Notegenerator 成员链接到Track 的成员,但我不知道该怎么做。

#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;
}

我想过做这样的事情,但它不起作用:

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

错误

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.

【问题讨论】:

  • 错误消息似乎很清楚这里发生了什么。

标签: c++ pointers reference member


【解决方案1】:

track.generator 已经是指向Generator 的指针,您不需要获取它的地址。

留在身边

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

更新代码:http://ideone.com/fAA4JX

【讨论】:

    【解决方案2】:

    正如编译器告诉你的,这一行:

    Note n = Note(&track.generator);
    

    尝试构造一个Note 并向其构造函数提供一个Generator**(因为track.generator 的类型为Generator*&amp;track.generator 的类型为Generator**)。

    但是,您的 Note 类构造函数接受 Generator*,而不是 Generator**。只需这样做(注意,这里不需要复制初始化,而是使用直接初始化):

    Track track;
    Note n(track.generator);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-13
      • 2018-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 2023-03-27
      相关资源
      最近更新 更多