Myk*_*huk 3 c++ templates operator-overloading
template< typename T >
double GetAverage(T tArray[], int nElements)
{
T tSum = T(); // tSum = 0
for (int nIndex = 0; nIndex < nElements; ++nIndex)
{
tSum += tArray[nIndex];
}
// convert T to double
return double(tSum) / nElements;
};
template <typename T>
class pair {
public:
T a;
T b;
pair () {
a=T(0);
b=T(0);
} ;
pair (T a1, T b1) {
a=a1;
b=b1;
};
pair operator += (pair other_pair) {
return pair(a+other_pair.a, b+other_pair.b);
}
operator double() {
return double(a)+ double(b);
}
};
int main(void)
{
pair<int > p1[1];
p1[0]=pair<int >(3,4);
std::cout<< GetAverage <pair <int >>(p1,1) <<"\n";
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么它打印0而不是3.5.
当我从C++复制代码时- 如何重载operator + =?一切都很好.但我无法理解我犯了什么错误
pair operator += (pair other_pair) {
return pair(a+other_pair.a, b+other_pair.b);
}
Run Code Online (Sandbox Code Playgroud)
应该
pair &operator += (const pair &other_pair) {
a += other_pair.a;
b += other_pair.b;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
您需要修改成员this并返回对其的引用*this,而不是新对象.other_pair作为一个const reference代替而传递也是一个好主意by value.
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |