没有已知的从std :: ostream *转换为std :: ostream&

时间:2013-09-27 21:41:53

标签: c++

我有以下代码:

class A {
public:
    ...
    C *func() { ... }
    void func2() { ... }
    ...
};

class B {
public:
    ...
    B(std::ostream &s, A *curr);
    ...
};

class C {
public:
    ...
    ostream *stream;
    ...
}

void A::func2() {
    ...
    std::ostream *astream = func()->stream;
    B *env = new B(astream, this);
    ...
}

但是我在B *env = new B(astream, this);行上收到以下错误:

myfile.cc:680:86: error: no matching function for call to ‘B::B(std::ostream*&, A* const)’
myfile.cc:680:86: note: candidates are:
myfile.h:194:2: note: B::B(std::ostream&, A*)
myfile.h:194:2: note:   no known conversion for argument 1 from ‘std::ostream* {aka std::basic_ostream<char>*}’ to ‘std::ostream& {aka std::basic_ostream<char>&}’

我不确定如何解决这个问题,并希望得到任何意见。

2 个答案:

答案 0 :(得分:2)

指针和引用不是一回事。我可能会质疑你在这里做了什么,但为了解决你的问题,请执行以下操作:

B *env = new B(*astream, this);

使用引用(例如 std::ostream &)时,正常变量的语法适用。

将来,您可以通过阅读错误消息来解决您的错误。错误“无已知转换”表示您尝试将一种类型分配给另一种不兼容的类型。它告诉你两种类型(一种是指针,另一种是引用)。现在您对指针和引用有了更多了解,您希望将来能够自己选择这些错误。 =)

答案 1 :(得分:0)

“astream”是一个指针。 B()构造函数需要引用。所以,选择是:

  • 将所有内容转换为指针或引用
  • 在需要引用时应用解除引用的指针:* astream