C++类模板问题求助!!!

2024-12-01 00:36:54
推荐回答(4个)
回答1:

#include
using namespace std;

template
class MyType
{
public:
MyType():m_val(0){}
MyType(Type val):m_val(val){}

MyType operator+(MyType &r)
{
MyType h;
h.m_val=m_val+r.m_val;
return h;
}

MyType operator-(MyType &r)
{
MyType h;
h.m_val=m_val-r.m_val;
return h;
}

Type getValue() {return m_val;}
private:
Type m_val;
};

int main()
{
MyType s1(10), s2(-5), s3;
MyType 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());

cin.get();
return 0;
}

回答2:

s1.value = 10 s2.value = -5 s3.value = 5
s4.value = 10.3 s5.value = 5.2 s6.value = 5.1

回答3:

template< class T >
class MyType
{
public:
MyType( T& t )
:
__value( t )
{
}
const T& getValue() const { return __value; }
private:
T __value;
};

回答4:

template
class MyType
{
public:
MyType() {}
MyType(const T& t) : t_(t) {}
~MyType() {}

public:
const MyType& operator+(const MyType& t)
{
t_ += t.getValue();
return *this;
}

const MyType& operator-(const MyType& t)
{
t_ -= t.getValue();
return *this;
}

void operator=(const T& t)
{
t_ = t.getValue();
}

const T& getValue() const
{
return t_;
}

private:
T t_;
};

临时写了个 希望对你有所帮助