无法在没有对象的情况下调用成员函数(尽管我相信我确实初始化了它)

Cannot call member function without object (though I believe I did initialize it)

本文关键字:相信我 管我 初始化 函数 对象 成员 调用 情况下      更新时间:2023-10-16
嗨,我

正在尝试为我的复数类定义我自己的 sqrt func,并在命名空间My_code调用它,这是在全局 main 方法中实现的。

当我尝试编译和运行代码时,

auto z2 = complex::sqrt(z);

不通过编译器。

我试过打印初始化的复数 z,效果很好。我还尝试了其他函数,例如 z 上的重载运算符,它们也可以正常工作。我不确定我的问题出在哪里。

//defining a new complex class and a function using your own namespace
#include <cmath>
#include <utility>
#include <iostream>
namespace My_code{
class complex{
    double re, im;
public:
    complex(double r, double i): re(r), im(i) {}
    complex(double r): re(r), im(0) {}
    complex() : re(0), im(0) {}
    double real() const { return re; }
    double imag() const { return im; }
    complex& operator += (complex z){
        re += z.re;
        im += z.im;
        return *this;
    }
    complex& operator -= (complex z){
        re -= z.re;
        im -= z.im;
        return *this;
    }
    auto sqrt(const complex& number);
};
    auto complex::sqrt(const complex& number){
        auto re = number.real();
        auto im = number.imag();
        auto modulus = std::sqrt(re*re + im*im);
        auto x_sq = (re + modulus)/2;
        auto y_sq = modulus - x_sq;
        if(im < 0){
            //x & y are of opposite signs
            auto value = std::make_pair(complex(std::sqrt(x_sq), - std::sqrt(y_sq) ), complex(-std::sqrt(x_sq), std::sqrt(y_sq))); //tuple
            return value;}
        else{
            //x&y are of same signs
            auto value = std::make_pair(complex(std::sqrt(x_sq), std::sqrt(y_sq)), complex(-std::sqrt(x_sq), -std::sqrt(y_sq))); //tuple
            return value;}
    }
    int main();
}

int My_code:: main(){
    complex z {8, -6};
    auto z2 = complex::sqrt(z);
    //auto z3 = z2.first;
    //std::cout << '{' << z3.real() << ',' << z3.imag() << "}n";
    std::cout << '{' << z.real() << ',' << z.imag() << "}n";
    return 0;
}
int main(){
    My_code::main();
    return 0;
}

我希望我的复数sqrt函数能给我一对复数,即(3,-1)和(-3,1)。

不能在没有对象的情况下调用成员函数

正确。只能使用成员访问运算符调用非静态成员函数。成员访问运算符需要一个对象作为左侧参数。

您可以像这样调用sqrt函数:

complex z1 {8, -6};
complex z2 {8, -6};
auto z3 = z1.sqrt(z2);

也就是说,您从不使用左侧参数的成员,因此不清楚为什么您将函数声明为非静态成员函数。您可能打算改为声明静态成员函数。可以在没有成员访问运算符的情况下调用静态成员函数,完全使用您尝试用于非静态成员函数的语法。

相关文章: