在泛型编程的家庭作业中,程序没有编译。我应该通过仅将代码插入指定位置并更改其他内容来解决此问题。我试图通过重载运算符来使编译器理解它们对该自定义类型的含义,但我仍然得到相同的错误。我现在不知所措。
#include <iostream>
using namespace std;
template <typename T>
struct TripleData {
T m_first;
T m_second;
T m_third;
T getMean() {
return (m_first + m_second + m_third)/3;
}
// INSERT CODE HERE
void operator = (const T & value) {
m_first = m_second = m_third = value;
}
void operator += (const TripleData & tridata) {
m_first += tridata.m_first;
m_second += tridata.m_second;
m_third += tridata.m_third;
}
T & operator / (const T & divisor) {
return m_first/divisor;
}
//END OF INSERTED CODE
};
template <typename T, int N>
class GenericStaticMatrix {
T m_data[N];
public:
T & operator()(int i) {
return m_data[i];
}
int getSize() const {
return N;
}
T getMean() const {
T sum = 0; //Error: conversion from 'int' to non-scalar type 'TripleData<double>' requested
for (int i=0;i<N;i++) sum+=m_data[i];
T ret = sum/(double)N; //Error: conversion from 'double' to non-scalar type 'TripleData<double>' requested
return ret;
}
};
int main() {
const int size = 10;
int i;
GenericStaticMatrix<TripleData<double>,size> gsm_tdd;
for (i=0;i<size;i++) {
gsm_tdd(i).m_first = 1.1 + i;
gsm_tdd(i).m_second = 2.2 + i;
gsm_tdd(i).m_third = 3.3 + i;
}
cout << gsm_tdd.getMean().m_first <<endl;
cout << gsm_tdd.getMean().m_second <<endl;
cout << gsm_tdd.getMean().m_third <<endl;
return 0;
}
提前致谢!
答案 0 :(得分:2)
需要为TripleData<double>
一般运行的代码是:
T sum = 0; // (A)
sum += m_data[i]; // (B)
T ret = sum / (double)N; // (C)
只需从此代码暗示的隐式接口向后工作。
// (A) implies non-explicit construction from an int
TripleData(int );
// (B) implies operator+=, you have this one almost right
TripleData& operator+=(const TripleData& rhs);
// (C) implies division by a **scalar** - this should NOT modify the object
TripleData operator/(double ) const;
您完全错过了(A)
- 您编写了一个赋值运算符,但T x = y;
并非分配,而是copy-initialization。 (B)
基本上没问题,(C)
您采用了错误类型的操作数。我们除以double
,而不是TripleData<double>
。