舉例來說:
class Employee {
public:
Employee() { id_ = count_++; }
unsigned id() const { return id_; }
private:
static unsigned count_;
unsigned id_;
}
unsigned Employee::count_ = 0;
定義==運算子
bool operator ==(const Employee& lhs, const Employee& rhs)
{
return lhs.id() == rhs.id();
}
於Test Case
Employee employee1;
Employee employee2;
QCOMPARE(empolyee1, employee2);
如此,執行Unit Test會跑出Compare values are not the same。但不會像比較double等內定型別一樣,列出Actual與Expected。
若要希望QCOMPARE自定類別也可列出Actual與Expected,需explicit template specialization QTest::toString(const T&):
namespace QTest {
template <>
char* toString(const Employee& employee)
{
QByteArray ba = "Employee, id = ";
ba += QByteArray::number(employee.id());
return qstrdup(ba.data());
}
}
如此,會跑出
Actual (employee1): Employee, id = 0
Expected (employee2): Employee, id = 1
假使希望對class template做相同的事:
template <unsigned _rowCount
class Vector {
public:
double& operator ()(unsigned row) { return data_[row-1]; }
double operator ()(unsigned row) const {return data_[row-1]; }
private:
double data_[_rowCount];
}
==運算子:
template <unsigned _rowCount>
bool operator ==(const Vector<_rowcount>& lhs, const Vector<_rowcount>& rhs>
{
for (unsigned row = 1; row <= _rowCount; ++row) {
if (lhs(row) != rhs(row)) return false;
}
return true;
}
class template之toString之寫法較特殊:
namespace QTest {
template <typename T, unsigned _rowCount
char* toString(const Vector<_rowcount>& v)
{
QByteArray ba = "Vector(";
for (unsigned row = 1; row <= _rowCount; ++row) {
ba += QByteArray::number(v(row));
ba += (row != _rowCount) ? ", " : ")";
}
}
}
儘管T未使用,仍不可只寫<>
先前Employee之toString也可改寫為<typename T>,脫褲子放屁就是了。
Vector<3> vector1;3>
vector1(1) = vector1(2) = vector1(3) = 1;
Vector<3> vector2;3>
vector2(1) = vector2(2) = vector2(3) = 2;
QCOMPARE(vector1, vector2);
如此,會跑出
Actual (vector1): Vector(1, 1, 1)
Expected (vector2): Vector(2, 2, 2)
沒有留言:
張貼留言