引用不同类中的指针成员

编程入门 行业动态 更新时间:2024-10-28 06:35:47
本文介绍了引用不同类中的指针成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有注和跟踪类, * generator 成员。当我创建新的注意对象时,我想链接生成器成员注意到跟踪,但我不知道如何做。

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);

错误

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: ideone/E38ibe#sthash.V3QMcYJQ.dpuf

此处的示例。

推荐答案

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

As the compiler is telling you, this line:

Note n = Note(&track.generator);

尝试构建注意 生成器** 到它的构造函数中(因为 track.generator 有类型 Generator * ,& track.generator 有类型 Generator ** )。

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

但是, Note 类构造函数接受 Generator * ,而不是 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);

更多推荐

引用不同类中的指针成员

本文发布于:2023-11-08 09:32:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569011.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   类中   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!