本次作业中,很多采用工程的方式来写作业,但是都存在部分问题,下面是我写的工程方式的参考答案,如果有疑问,欢迎来找我讨论。
本次作业有以下几个问题:
1.大部分同学都受上次作业的影响,把成员变量声明成public作用域,这个其实是个很糟糕的习惯,用一个很不恰当的比喻,你愿意把你自己的隐私部位暴露给别人看么,设置让别人来触摸?试想C++为什么会有封装这个术语呢?以及今后大家选修侯捷老师的设计模式这门课会学习的OCP法则,其实都说明了这个道理,这些成员对于一个类来说就是隐私部位,就我个人而言,只有static字段说明的成员变量才会用public修饰,希望同学们把这个误区改过来。
2.还有大部分同学的拷贝构造函数都有问题,希望大家能够看一下我是怎么写的,给大家一个启示。
说明:
1.本次作业,一个函数10分,总共有8个函数;一个函数有问题,10分全扣;
2.以后大家测试函数一定要写,对每个成员函数,包括构造函数、甚至是析构函数(大家不妨在构造函数和析构中输出一些内容到屏幕上,比如这个类生成或者是分解)
不写测试函数我都会扣分,而且测试文件都要把输出什么都写清楚,就像我写的那样,我就直接看大家的exe文件就一目了然了。
3.大家都要将生成的exe文件都放到服务器上,谢谢大家的配合
头文件这样的写法可以方式循环引用
Vertex.h
#ifndef _VERTEX_H_
#define _VERTEX_H_
#include<cmath>
#include <iostream>
using namespace std;
class Vertex
{
public:
Vertex();
Vertex(float x,float y,float z);
Vertex(const Vertex &v);
//下面重载的4个操作符一般不用引用返回,具体原因google
//如果是重载operator=,就要引用返回
Vertex operator+ (const Vertex &v) const;
Vertex operator- (const Vertex &v) const;
bool operator==(const Vertex &v) const;
bool operator!=(const Vertex &v) const;
double length() const;
//引用返回,因为可以连续输出,比如cout<<a<<b<<c;
friend ostream& operator<<(ostream& os, const Vertex &v);
private:
float _fx;
float _fy;
float _fz;
};
#endif/* _VERTEX_H_ */
Vertex.cpp
#include "Vertex.h"
Vertex::Vertex(){ _fx=0; _fy=0; _fz=0; }
Vertex::Vertex(float x, float y, float z):_fx(x), _fy(y), _fz(z){}
Vertex::Vertex(const Vertex& v){ _fx=v._fx; _fy=v._fy; _fz=v._fz; }
Vertex Vertex::operator+(const Vertex &v) const
{
Vertex vertex;
vertex._fx=this->_fx+v._fx;
vertex._fy=this->_fy+v._fy;
vertex._fz=this->_fz+v._fz;
return vertex;
}
Vertex Vertex::operator-(const Vertex &v) const
{
Vertex vertex;
vertex._fx=this->_fx-v._fx;
vertex._fy=this->_fy-v._fy;
vertex._fz=this->_fz-v._fz;
return vertex;
}
bool Vertex::operator==(const Vertex &v)const
{
if(v._fx==_fx && v._fy == _fy && v._fz==_fz)
return true;
else
return false;
}
bool Vertex::operator!=(const Vertex &v)const
{
if(v._fx==_fx && v._fy==_fy && v._fz==_fz)
return false;
else
return true;
}
double Vertex::length() const
{
return sqrt(_fx*_fx+_fy*_fy+_fz*_fz);
}
//函数名前前面不能有Vertex::限定,因为这个函数不是Vertex的,而是系统的ostream的一个函数
ostream& operator<<(ostream& os, const Vertex &v)
{
os<<"("<<v._fx<<","<<v._fy<<","<<v._fz<<")";
return os;
}
main.cpp
#include "Vertex.h"
using namespace std;
void main()
{
Vertex a;
Vertex b(1, 2, 3);
Vertex c(3, 4, 5);
Vertex d(3, 4, 5);
cout<<"a = "<<a<<endl
<<"b = "<<b<<endl
<<"c = "<<c<<endl
<<"d = "<<d<<endl;
if(b != c)
cout<<"b != c"<<endl;
else
cout<<"b == c"<<endl;
if(c == d)
cout<<"c == d"<<endl;
else
cout<<"b != d"<<endl;
Vertex e;
e = b + c;
cout<<"e = b + c = "<<e<<endl;
Vertex f;
f = b - c;
cout<<"f = b - c = "<<f<<endl;
cout<<"|b| = "<<b.length()<<endl;
return;
}