c++ - 如何在两个实例中使用值进行计算?

标签 c++ class instance

我们被要求在主函数中创建两个实例并进行计算,但我不知道并且总是有错误信息... 这是 Complex.h

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <ctime>

class Complex
 {
   private:
   int real1,real2;
   double imag1,imag2;

   public:
   /*Complex();
   ~Complex(){  };*/
   void setReal(int newreal);/*setter function*/
   void setImag(double newimag);

   int getReal();/*getter function*/
   double getImag();

    void printcom(int real1, double imag1, int real2, double imag2);/*print the entered      values in mathematical form of complex number*/

   void Conjugate(int real1, double imag1, int real2, double imag2);/*calculations for complex number*/
   void Add(int real1, double imag1, int real2, double imag2);
   void Subtract(int real1, double imag1, int real2, double imag2);
   void Multiply(int real1, double imag1, int real2, double imag2);

 };

complex.cpp 太长,所以我没有在这里展示它,但它起作用了。

然后是主要的测试函数:testcomplex.cpp

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <ctime>
#include "Complex.h"

using namespace std;

int main()
{
    Complex a,z,c;
    int real;
    double imag;

    cout << "The real part of the first complex number: "<<endl;
    cin >> real;
    a.setReal(real);
    cout << "The imaginary part of the first complex number: "<<endl;
    cin >> imag;
    a.setImag(imag);
    cout << "The real part of the second complex number: "<<endl;
    cin >> real;
    z.setReal(real);
    cout << "The imaginary part of the second complex number: "<<endl;
    cin >> imag;
    z.setImag(imag);

    c.printcom(a.real1,a.imag1,z.real1,imag1);
    c.Conjugate(a.real1,a.imag1,z.real1,imag1);
    c.Add(a.real1,a.imag1,z.real1,imag1);
    c.Subtract(a.real1,a.imag1,z.real1,imag1);
    c.Multiply(a.real1,a.imag1,z.real1,imag1);

    return 0;
}

最佳答案

你的作业中写得很清楚“我们被要求在主函数中创建两个实例并进行计算

意思是Complex类应该写成只定义一个复数。那么一个复数怎么会有两个实部和虚部呢? 因此,而不是

class Complex
 {
   private:
   int real1,real2;
   double imag1,imag2;

必须有

class Complex
 {
   private:
   int real;
   double imag;

我也不明白为什么类的实际部分的类型是 int 而 imagenary 的类型是 double

成员函数的声明也不正确。例如函数 printcom 应该声明为

void printcom() const;

或函数 Add 应声明为成员函数 as

const Complex Add( const Complex &rhs ) const;

作为非成员函数

const Complex Add( const Complex &lhs, const Complex &rhs );

关于c++ - 如何在两个实例中使用值进行计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21973469/

相关文章:

java - 在 Java 中,为什么父类(super class)方法不能从子类实例访问 protected 或私有(private)方法/变量?

c++ - 如何从 C++ 中的另一个实例访问一个实例的信息?

C++ 在无序树中查找具有最高值的节点

class - Dart - 对象实例化和方法调用中的错误

java - Java中如何从父类(super class)访问子类?

java - 另一个类中的 SQL 更新

c++ - 关于 C++ 中的复制控制

C++父类调用子虚函数

c++ - 在派生类中重载基类函数

c# - 在 2 个 dll 中具有命名空间名称的不明确类