无法在没有对象的情况下调用成员函数(尽管我相信我确实初始化了它)
Cannot call member function without object (though I believe I did initialize it)
嗨,我
正在尝试为我的复数类定义我自己的 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);
也就是说,您从不使用左侧参数的成员,因此不清楚为什么您将函数声明为非静态成员函数。您可能打算改为声明静态成员函数。可以在没有成员访问运算符的情况下调用静态成员函数,完全使用您尝试用于非静态成员函数的语法。
相关文章:
- 如何指定我希望我的LIB链接到的DLL文件?-Visual Studio 2019
- 我认为我的代码很好,但它在 cin a 之后停止并且没有进一步?
- 在 fork() 之后,我在我的程序中不断得到相同的 pid
- 我觉得我放入结构中的输入代码可以压缩,关于如何在保持代码简短的同时保持数据个性化的任何建议?
- 我把我的编译器从32位转换为64位,但我仍然不能使用超过2GB:(为什么
- 即使在我为我的应用程序授予管理员后也无法从 Windows 系统复制目录
- 在我为我的二维向量提供第一个值后控制台关闭
- Fread C++ in C#.我知道我需要字节缓冲区,但并不完全在那里
- 当我使用我的向量名称后跟包含整数变量的括号时,括号是什么意思
- 在一个文件中定义多个类时,我发现我的主函数无法访问较低类中的函数
- 当我编译我的程序时,它显示"分段错误(或)分段错误(核心转储)
- 谁能帮我做我自己的矢量类
- 当我运行我的程序时,即使"user"输入数字||C++ 绘画作业
- 为什么我允许我为std :: vector设置end()
- 谁能告诉我为什么我的程序在无限的循环中进行
- 我在变量上收到 3 个 C4703 错误,我认为我已经正确初始化了,但我不确定我错过了什么
- 调用'maps::size(char [20], char&)'没有匹配函数,但我认为我的方法有
- 有人可以告诉我为什么我在这里使用sizeof()函数无法找到数组的长度
- 为什么我在我的C 代码中获得链接命令失败错误
- 我从我的字符串函数返回到主函数