C++非静态成员引用必须相对于特定对象

C++ Nonstatic member referencing must be relative to specific object

本文关键字:相对于 对象 静态成员 引用 C++      更新时间:2023-10-16

这个复数程序应该从txt文档中获取三个参数,第一个参数指示后面的两个参数是极坐标形式还是矩形形式的数字,并输出以矩形和极坐标形式给出的每个复数。这里显示了头文件和源代码。txt文档的格式如下:

p 50 1.2
r 4 0.8
r 2 3.1
p 46 2.9
p 3 5.6

如果没有在类声明中将int inputfile()函数声明为静态,则生成会给出错误"非法调用非静态成员函数"。

通过函数的静态声明(如下所示),构建在函数定义inputfile()内引用类成员Pfirst、Psecond、Rfirst和Rsecond时会出现错误,即"对非静态成员的非法引用"。

成员声明也不能变为静态的,因为类将无法初始化构造函数中的参数。

如何绕过这个"静态"问题?

#define Complex_h
class Complex
{
char indicator;
const double pi;

public:
double Pfirst, Psecond, Rfirst, Rsecond;
Complex(char i = 0, double Pf = 0, double Ps = 0, double Rf = 0, double Rs = 0, const double pi = 3.14159265) // with default arguments (= 0)
: indicator(i), Pfirst(Pf), Psecond(Ps), Rfirst(Rf), Rsecond(Rs), pi(pi) {}
~Complex();
void poltorect();
void recttopol();
static int inputfile();
};


#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include "Complex.h"
using namespace std;

int Complex::inputfile()
{
ifstream ComplexFile;
ComplexFile.open("PolarAndRectangular.txt");
string TextArray[3];
string TextLine;
stringstream streamline, streamfirst, streamsecond;
while (getline(ComplexFile,TextLine))
{
streamline << TextLine;
for (int j=0; j<3; j++)
{streamline >> TextArray[j];}
streamline.str("");
streamline.clear();
if (TextArray[0] == "r") 
{
streamfirst << TextArray[1];
streamfirst >> Rfirst;
streamsecond << TextArray[2];
streamsecond >> Rsecond;
cout << "Complex number in rectangular form is " << Rfirst << "," << Rsecond << endl;
void recttopol();
cout << "Complex number in polar form is " << Pfirst << "," << Psecond << endl;
}
else 
{   
streamfirst << TextArray[1];
streamfirst >> Pfirst;
streamsecond << TextArray[2];
streamsecond >> Psecond;
cout << "Complex number in polar form is " << Pfirst << "," << Psecond << endl;
void poltorect();
cout << "Complex number in rectangular form is" << Rfirst << "," << Rsecond << endl;
}
streamfirst.str("");
streamfirst.clear();
streamsecond.str("");
streamsecond.clear();
}
ComplexFile.close();
system("pause");
return 0;
}   

void Complex::recttopol()
{
Pfirst = sqrt((Rfirst*Rfirst)+(Rsecond*Rsecond));
Psecond = (atan(Rsecond/Rfirst))*(pi/180);
}
void Complex::poltorect()
{
Rfirst = Pfirst*(cos(Psecond));
Rsecond = Pfirst*(sin(Psecond));
}

int main()
{
Complex::inputfile();
system("pause");
return 0;
}

您忘记创建类型为Complex的对象。

使您的inputfile()方法非静态并执行:

int main()
{
Complex complex; // Object construction.
complex.inputfile();
system("pause");
return 0;
}