我有這個類:推斷如果傳遞給一個funcion參數在操作等於參數
A a;
A b;
A c=func(a,b);
但問題:
class A
{
public:
//copy and move constructor,operator=
A func(const A& a,const A& b)
{
A c;
//do some stuff...
return c;
}
};
它,當我以這種方式使用它工作正常是當我這樣使用它:
A a;
A b;
a=func(a,b);
它做一些不必要的東西(使c和在我的課調用construc Tor是費時!)
我想知道,如果是等於把它傳遞給函數,那麼我不作c和就地
做的東西想。我來了一會兒後一個變量了此解決方案:
class A
{
public:
//copy and move constructor and operator=
A func(const A& a,const A& b)
{
A c;
//do some stuff...
return c;
}
A func(const A& a,const A& b,bool inPlace)
{
if(!inPlace)
return func(a,b);
else
{
//const-cast a then do stuff on a
return a;
}
}
};
現在它工作正常:
A a;
A b;
A c=func(a,b);
a=func(a,b,true);
但它仍然不工作:
A a;
A b;
b=func(a,b,true);
因此需要func
的另一個重載。
但它似乎是一個糟糕的設計。任何更好的想法,使這個類?
注意,我不想做FUNC這樣的:
void func(const A& a,const A& b,A& result)
(很遺憾有關問題的標題我不能找到一個更好的:))
編輯
我的構造函數看起來像這樣:
A(unsigned int SIZE)
{
// all of these are vectors and SIZE is about 1k
realData_.reserve(SIZE);
timePerUnit_.reserve(SIZE);
prob_.reserve(SIZE);
//....
// some math stuff for filling them
}
請問您可以添加'class A'的構造函數嗎? – HadeS
在類A中使用運算符重載=運算符。這使您可以正確分配返回的對象。 – vathsa
您是否定義了移動賦值運算符? –