简体   繁体   中英

No known conversion from std::ostream* to std::ostream&

I have the following code:

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

However I am getting the following error on the B *env = new B(astream, this); line:

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>&}’

I'm not sure how to solve this issue and would appreciate any input.

Pointers and references are not the same thing. I might question exactly what you're doing here, but to solve your problem as it stands, do this:

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

When using a reference ( eg std::ostream & ), the syntax of normal variables applies.

In future, you can work out your mistake by reading the error message. The error "no known conversion" means you are trying to assign one type to another type that is incompatible. It tells you the two types (one is a pointer and the other is a reference). Now you know a little more about pointers and references, you will hopefully pick these errors up yourself in future. =)

"astream" is a pointer. B() constructor expects a reference. So, the choice is:

  • Convert everything to pointers or references
  • Apply dereferenced pointer whenever you need a reference: *astream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM