讨厌的C++
Category : C++
其实我并不会C++,只是这次她的作业是要求用C++来做,我才硬着头皮去学C++的
这是她昨天的一道题:
#include<stdio.h>
#include<iostream>
using namespace std;
template<class T>
class MyType {
public:
MyType(){
this->value = 0;
};
MyType(T value){
this->value = value;
};
T getValue() {
return this->value;
};
T operator +(const MyType &x) const {
return this->value + x.value;
};
T operator -(const MyType &x) const {
return this->value - x.value;
};
void operator =(const MyType &x) {
this->value = x.value;
};
private:
T value;
};
int main(){
MyType<int> s1(10),s2(-5),s3;
MyType<double> s4(10.3),s5(5.2),s6;
s3=s1+s2;
s6=s4-s5;
printf("s1.value=%d s2.value=%d s3.value=%d\n",s1.getValue(),s2.getValue(),s3.getValue());
printf("s4.value=%2.1f s5.value=%2.1f s6.value=%2.1f\n",s4.getValue(),s5.getValue(),s6.getValue());
return 0;
}
里面用到了多态和操作符的重载
template
T operator +(const MyType &x) const {
return this->value + x.value;
};
是对操作符的重载,这段代码是对"+"的重载,注意,"this->"表示引用当前对象的属性,相当于java中的"this.",不过C++中是用"->"而不是用".",当引用对象名的时候,就用"."而不是"->"了,这是一个需要特别注意的地方
由于C++是强类型的语言,所以所有的变量和方法都必须声明类型和返回值类型,习惯了也就好了

