复数打印程序出现故障

时间:2011-01-14 10:32:52

标签: c++

我已经开始研究C ++语言。我对它很新。该程序从用户那里得到一个复杂的数字并将其打印出来。但它给了我很多错误,比如,

prog.cpp: In function ‘int main()’:
prog.cpp:26: error: ‘GetReal’ was not declared in this scope
prog.cpp:26: error: ‘SetReal’ was not declared in this scope
prog.cpp:27: error: ‘GetImag’ was not declared in this scope
prog.cpp:27: error: ‘SetImag’ was not declared in this scope
prog.cpp:28: error: ‘print’ was not declared in this scope
prog.cpp: At global scope:
prog.cpp:34: error: expected unqualified-id before ‘)’ token
prog.cpp:40: error: expected unqualified-id before ‘float’
prog.cpp:40: error: expected `)' before ‘float’
prog.cpp: In function ‘void SetImag(float)’:
prog.cpp:64: error: ‘real’ was not declared in this scope
prog.cpp: In function ‘void SetReal(float)’:
prog.cpp:68: error: ‘imag’ was not declared in this scope
prog.cpp: In function ‘void print()’:
prog.cpp:73: error: ‘Cout’ was not declared in this scope
prog.cpp:73: error: ‘real’ was not declared in this scope
prog.cpp:73: error: ‘imag’ was not declared in this scope

以下是代码:

/*
Date=13 January 2011
Program: To take a complex number from the user and print it on the screen */

/*Defining a class*/
#include <iostream>
using namespace std;
class complex
{
float real;
float imag;
public:
complex();
complex(float a,float b);
float GetReal();
float GetImag();
void SetReal();
void SetImag();
void print();
};

int main()
{
complex comp;
SetReal(GetReal());
SetImag(GetImag());
print();
}

complex()
{
real=0;
imag=0;
}

complex(float a,float b)
{
real=a;
imag=b;
}

float GetReal()
{
float realdata;
cout<<"Enter Real part:"<<endl;
cin>>realdata;
return realdata;
}

float GetImag()
{
float imagdata;
cout<<"Enter Imaginary part"<<endl;
cin>>imagdata;
return imagdata;
}

void SetImag(float a)
{
real=a;
}
void SetReal(float b)
{
imag=b;
}

void print()
{
printf("The Complex number is %f+%fi",real,imag);
}

2 个答案:

答案 0 :(得分:5)

由于GetReal()等被声明为complex类的一部分,因此您应该在您创建的对象上调用它们:

complex comp;
comp.SetReal(comp.GetReal());
comp.SetImag(comp.GetImag());
comp.print();

同样,您需要确定complex构造函数的实现范围:

complex::complex()
{
  real=0;
  imag=0;
}

这同样适用于您帖子中未显示的其他成员函数。

答案 1 :(得分:0)

在main函数中,您需要在类的实例上调用GetReal和SetReal: e.g。

Complex comp;
comp.SetReal();
...

此外,您的方法体不绑定到类,它们在全局命名空间中浮动。你需要定义它们:

void Complex::SetReal() {} //etc

希望这有帮助