C++程序求助高手,急!在线等!!!满意加悬赏

定义类型vec4为具有4个float数的向量。为vec4重载运算符“[ ]”,使其检查参数的合法性。并为向量和向量之间、向量和浮点数之间的各种组合运算定义运算符 +、=、+=
为什么我在网页上看不到答案啊?明明提示有的啊???

知道网友张双峻在 2012年12月3日 23:34 回答了您的提问。
问:C++程序求助高手,急!在线等!!!满意加悬赏
答:#include<iostream>
using namespace std;
class vector

怎么办,对不起,邮件提示有,但我找不到你的答案,等电脑抽完疯一定采纳......

#include <iostream>
using namespace std;
class vec4{
float v[4];
public:
vec4(float *pv=0){ //构造函数
if(pv!=0)
for(int i=0; i<4; i++) v[i]=pv[i];
else
for(int i=0; i<4; i++) v[i]=0;
}
float& operator[](int i){
if(i<0 || i>3){
cout <<"错误:下标越界。\n";
exit(1);
}
return v[i];
}
vec4& operator=(vec4& ov){
for(int i=0; i<4; i++) v[i]=ov[i];
return *this;
}
vec4& operator=(float& f){ //每个元素都赋值为f
for(int i=0; i<4; i++) v[i]=f;
return *this;
}
vec4 operator+(vec4& ov){ //对应元素相加
vec4 t;
for(int i=0; i<4; i++) t.v[i]=v[i]+ov.v[i];
return t;
}
vec4 operator+(float f){ //每个元素都加f
vec4 t;
for(int i=0; i<4; i++) t.v[i]=v[i]+f;
return t;
}
vec4& operator+=(vec4& ov){
for(int i=0; i<4; i++) v[i]+=ov[i];
return *this;
}
vec4& operator+=(float& f){ //每个元素都赋值为f
for(int i=0; i<4; i++) v[i]+=f;
return *this;
}
void display(){
for(int i=0; i<4; i++) cout <<v[i] <<" ";
cout <<endl;
}
};
int main(){
float a1[4]={1.1f,3.3f,5.5f,7.7f}, a2[4]={2.2f,4.4f,6.6f,8.8f};
float f1=1.5f, f2;
vec4 v1(a1), v2(a2), v3;
v1.display();
v2.display();
v3=v1+v2;
v3.display();
v3=v1+f1;
v3.display();
v1+=v2;
v1.display();
v2+=f1;
v2.display();
f2=v1[2];
cout <<"f2=" <<f2 <<endl;
f2=v1[4];
return 0;
}
温馨提示:答案为网友推荐,仅供参考
相似回答