C++ 复数类程序调试及分析

程序代码 (exp_101.cpp):

#include <iostream>
#include <math.h>
using namespace std;

class complex
{
private:
    double real;
    double imag;
public:
    void set_complex(double r, double i)
    {
        real = r; imag = i;
    }
    double get_real()
    {
        return real;
    }
    double get_imag()
    {
        return imag;
    }
    double get_abs()
    {
        double t;
        t = sqrt(real * real + imag * imag);
        return t;
    }
};

int main()
{
    complex A;
    A.set_complex(3.0, 4.0);
    cout 'real of complex A=';
    cout << A.get_real() << endl;
    cout 'imag of complex A=';
    cout << A.get_imag() << endl;
    cout 'abs of complex A= ';
    cout << A.get_abs() << endl;
    return 0;
}

问题与答案:

(1) 程序的输出结果为:

real of complex A=3
imag of complex A=4
abs of complex A= 5

(2) 成员函数(方法)的作用:

  • set_complex(double r, double i): 给复数的实部和虚部赋值。
  • get_real(): 获取复数的实部值。
  • get_imag(): 获取复数的虚部值。
  • get_abs(): 获取复数的模长。

(3) 将 main() 函数中的语句行 cout << A.get_real() << endl; 改为 cout << A.real << endl;,重新编译程序,将出现编译错误,其原因是 real 是 complex 类的私有成员变量,不能直接访问。

解释:

在 C++ 中,类成员变量默认是私有的,这意味着它们只能在类的内部访问。如果尝试在类的外部直接访问私有成员变量,将会导致编译错误。

总结:

这个程序示例展示了面向对象编程中的封装概念。通过将数据成员声明为私有,并提供公有成员函数来访问和修改这些数据,可以保护数据的完整性和一致性,并提高代码的可维护性。

C++ 复数类程序调试及分析 - 详解代码功能与错误原因

原文地址: https://www.cveoy.top/t/topic/nfD0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录