模板我有是:錯誤而
template <class T>
class Shape {
T val,val_new;
public:
Shape(T initval)
{
val=initval;
}
T get()
{
return val;
}
void set (T newval)
{
val_new = newval;
}
void copy()
{
val= val_new;
}
};
使用此模板的類是:
#include <iostream>
#include<math.h>
using namespace std;
class Rectangle
{
private:
Shape<TwoPoint> val;
bool incr_called, decr_called, load_called;
TwoPoint newval;
public:
Rectangle(TwoPoint i)
: val (Shape<TwoPoint> (i)) {}
Shape<TwoPoint> read()
{
return val;
}
void load(TwoPoint n)
{
load_called=1;
newval=n;
}
void increment()
{
incr_called=1;
}
void decrement()
{
decr_called=1;
}
void init()
{
incr_called=0;
decr_called=0;
load_called=0;
}
void actions()
{
if (load_called)
val.set(new TwoPoint(newval));
if(incr_called && !decr_called)
val.set((new TwoPoint(val.get())).plus(1));
if(!incr_called && decr_called)
val.set((new TwoPoint(val.get())).plus(-1));
}
};
的兩點類被定義爲:
class TwoPoint
{
int width;
int value;
public:
TwoPoint()
{
value=0;
width=0;
}
TwoPoint(int v, int w)
{
value=v;
width=w;
}
TwoPoint(const TwoPoint& t)
{
value= t.value;
width= t.width;
}
int getWidth()
{
return width;
}
int getValue()
{
return value;
}
TwoPoint & plus(int newval)
{
value+=newval;
return *this;
}
};
但有錯誤:
In member function 'void Rectangle::actions()':
error: request for member 'plus' in '(((TwoPoint*)operator new(8u)), (((*<anonymous>)
<unknown operator> TwoPoint<T>::get() [with T=TwoPoint]()), <anonymous>))', which is of non-class type 'TwoPoint*'
還有另一個錯誤:
In member function 'void Rectangle::actions()':
error: no pattern matching function for call to 'Shape<TwoPoint>::set(TwoPoint*)'
note: candidates are: void Shape<T>:: set<T> [with T=TwoPoint]
有兩個錯誤,當我在行動做類似的操作(),由於同樣的原因。有人可以解釋這些錯誤以及如何改進它們嗎? 有什麼辦法可以讓代碼更高效?
能否請您解釋一下 – 2012-02-18 11:48:44
@user:說明哪個部分? – 2012-02-18 11:49:02
我不明白內存泄漏部分 – 2012-02-18 11:51:13