简体   繁体   中英

Fixing “this” error in c++

I'm still new to c++ and I was wondering why I keep getting the error "invalid use of 'this' in non-member function" for every instance of "this" in my cpp file.

cpp file (just method)

ostream & operator<< (ostream & outS, Complex & rhs) {
  cout << this->real;
    if (this->imag < 0) {
        cout << "-";
        if (this->imag != -1)
            cout << (-this->imag);
        cout << "i";
    } else if (this->imag >0){
        cout << "+";
        if (this->imag != 1)
            cout << this->imag;
        cout << "i";

  return outS;
}

header file (part of)

public:
   friend ostream & operator<< (ostream&, Complex&);

I also seem to be getting the error "'Complx' does not name a type Complx::Complex (const Complex& object)" ^

cpp file

Complx::Complex (const Complex& object) {
  real = object.real;
  imag = object.imag;
}

header file

 public:
   Complex (const Complex&);     

Any help would be much appreciated, and I can post the rest of my code if needed (I figured just posting parts of it would be easier to read).

this refers to your current object -- the object that the method is a part of. When your method stands alone, it's not part of an object so this has no meaning. It appears that instead of this-> you intend to refer to rhs. .

In your operator<< , it is NOT a member of your class. Thus, it does not have this pointer, which is only for class non-static members.

class Complex
{
    double imag, real;
public:
    Complex(const _real=0.0, const _imag=0.0);
    Complex(const Complex&);

    // friend functions are not member of the class
    friend ostream& operator<< (ostream&, Complex&);

    // this is a member of the class
    Complex operator+(Complex& another)
    {
        // I am a member so I have 'this' pointer
        Complex result;
        result.real = this->real + another.real;
        result.imag = this->imag + another.imag;
        return result;
    }
};

ostream& operator<<(ostream& stream, Complex& rhs)
{
    // I do not have 'this' pointer, because I am not a member of a class
    // I have to access the values via the object, i.e. rhs
    stream << rhs.real << "+" << rhs.imag << 'i';
    return stream;
}

Yet my question is, why do you want to use 'friend operator<<'? IMHO it should not be a friend of the class, instead, the class should provide functions like double image() const { return this->imag; } double image() const { return this->imag; } , and the non-friend operator<< can access the values via these functions.

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