修复 C++ 中的"this"错误

Fixing "this" error in c++

本文关键字:this 错误 中的 C++ 修复      更新时间:2023-10-16

我还是c++的新手,我想知道为什么我的cpp文件中的每个"this"实例都会出现错误"在非成员函数中无效使用"this"。

cpp文件(just方法(

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

头文件(的一部分(

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

我似乎也收到了错误"Complex"没有命名类型Complex::Complex(const Complex&object("^

cpp文件

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

头文件

 public:
   Complex (const Complex&);     

任何帮助都将不胜感激,如果需要,我可以发布我的代码的其余部分(我认为只发布部分代码会更容易阅读(。

this指的是当前对象——该方法所属的对象。当您的方法单独存在时,它不是对象的一部分,因此this没有任何意义。似乎您要指的不是this->,而是rhs.

operator<<中,它不是类的成员。因此,它没有this指针,该指针仅用于类非静态成员。

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

然而,我的问题是,你为什么要使用"friend operator<lt;'?IMHO它不应该是类的朋友,相反,类应该提供类似double image() const { return this->imag; }的函数,非朋友operator<<可以通过这些函数访问值。

相关文章: