《电路计算C++与MATLAB》学习笔记(二)

来源:互联网 发布:男士脸型与发型知乎 编辑:程序博客网 时间:2024/05/22 01:57

在直流梯形网络的计算源程序中包含下列代码

#include "vector.cpp"

经过调试发现无法运行,网上搜索知不能直接包含另一工程文件。搜索解决问题时,发现需要把程序分为三部分,养成写代码的好习惯

(一)头文件,头文件此处为类的声明,以.h结尾

vector.h

class vector{public:int size; float *p;int ub;//上界(upper bound)=size-1vector();vector(int);~vector();float & operator[](int iv);}; 

(二)类的源文件,主要包含类的定义,数据成员与成员函数,文件后缀为.cpp

vector.cpp

#include "stdafx.h"#include <iostream>using namespace std;#include"vector.h"#include <stdlib.h>vector::vector() {size = 10;p = new float[size];//开辟大小为size的实数空间,并用指针p指向它ub = size - 1;}vector::vector(int n){if (n < 0) { cerr << "illegal vector size" << n << "\n"; exit(1); }size = n; p = new float[size]; ub = size - 1;}/*vector(n)*/vector::~vector() { delete p; }float & vector::operator[](int iv){if (iv >= 0 && iv <= ub)return p[iv];else {cerr << "illegal vector element\n"; exit(1);}}

此处类的源文件以.cpp结尾,所以依然加下列代码,其中一些是输入输出,最重要的是包含vector.h, 且不是<>, 而是" ",

#include "stdafx.h"#include <iostream>using namespace std;#include"vector.h"#include <stdlib.h>

(三)主函数main的源文件,以.cpp结尾

main.cpp

#include "stdafx.h"#include"vector.h"#include<iostream>using namespace std;void main(){vector a(3); vector b;vector &c = b;//对象c引用b,即c和b完全相同  a[0] = 4.5; b[0] = a[0]; cout << b[0];b[1] = 6.7; cout << " " << c[1] << endl;cin >> b[3];cout << "c[3]=" << c[3] << endl;cin >> a[3];//a[3]超界,所以输出illegal vector element  //b[3]输入数据为8.8  }

需要注意的是main主函数仍需要包含

#include "vector.h"

最后debug调试发现符合预期结果

(四)总结与问题

网上查找资料与书籍时,找到头文件包含的类型,此处为类的声明,其他包含的内容以后再补充

  • 函数原型
  • 使用#define或const定义的符号常量
  • 结构声明
  • 类声明
  • 模板声明
  • 内联函数

问题1

float& operator[](int iv);float& vector::operator[](int iv){if (iv >= 0 && iv <= ub)return p[iv];else {cerr << "illegal vector element\n"; exit(1);}

此函数没有理解明白,查找资料

问题2

#include <stdlib.h>//头文件的作用

参考文章:http://www.cplusplus.com/reference/cstdlib/exit/

stdlib.h是C标准函数库的头文件,声明了数值与字符串转换函数, 伪随机数生成函数, 动态内存分配函数, 进程控制函数等公共函数。本例中与exit(1), 函数联合使用

Status code.

if this is 0 or EXIT_SUCCESS, it indicates success.

If it is EXIT_FAILURE, it indicates failure.






原创粉丝点击