c++ - 复数打印程序出现故障

标签 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);
}

最佳答案

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

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

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

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

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

关于c++ - 复数打印程序出现故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4690119/

相关文章:

c++ - 使用 CPP 插件在 gradle 中编译 C++ 代码

c++ - 请提出一些算法来找到树中所有节点中到最远节点的距离最小的节点

c++ - 函数后的 const 如何优化程序?

c++ - 编写数据结构以对每个线程使用不同的缓存行以避免线程抖动?

c++ - 将 strcpy() 与指向 cstring 的指针一起使用时出现段错误

c++ - 使用 .h 扩展名

c++ - IDE 使用 Visual Studio,但跨平台配置使用 CMake

c++ - RapidJSON 库通过索引获取数组中的值

c++ - 发布版本中的缓存刷新问题

c++ - MSVC 2010 模板编译器问题