![](/img/trans.png)
[英]Inheriting from a templated class with operator overloading. ambiguous overload for 'operator*'
[英]c++ operator overloading. Function to get private value from overload
我在此類中無法獲得“打印”功能以獲取正確的總數
class PRN {
private:
typedef pair < string, int > P;
int sz, // map size – no of distinct words
cnt, // counter for printing
total; // no of words
public:
// constructor
PRN ( const int& s = 1, const int& c = 0, const int& t = 0 ){
cnt= c;
total = t;
sz = s;
}
void operator ( ) ( const P& p ){
total += p.second;
cout << total;
}// overloaded operator, where P is defined as
// typedef pair < string, int > P;
void print () const{
cout <<"no of words in output list : " << total << endl;
}
};
然后我打電話給我
PRN p (m.size());
for_each(m.begin(),m.end(),p);
p.print();
m是包含一些值(字符串,整數)的映射; 運算符之所以添加是因為我正在打印它們,並且可以看到它們正在被添加,但是當我調用p.print()時,它的“總計”返回零。
有什么建議么? 謝謝
問題在於for_each
的行為-標准不保證for_each
在執行工作時不會在內部復制p
。 結果,具有狀態的類似函數的對象通常無法與標准庫函數配合使用。 就我個人而言,我一直認為這種行為很奇怪,並且破壞了具有類似函數的對象的很多意義,但這就是我們要解決的問題。
根據使用方式的不同,通過使total
成為PRN
的靜態成員,您也許能夠或多或少地獲得所需的行為,從而所有PRN
對象使用的任何地方都只有一個total
值。 缺點是,在未來for_each
會拿起你離開,而不是從頭開始了,但你或許能夠做這樣具有的東西來緩和PRN
構造復位total
假設為零(即PRN
對象不壽命很長,並且創建位置與使用位置非常接近)。
另一種可能性是讓PRN
對象包含一個指向另一個實際包含總數的對象的指針,如下所示:
class PRN
{
private:
struct Storage
{
int total;
};
Storage *s;
public:
PRN():
s(new Storage)
{
}
~PRN()
{
delete s;
}
void operator()(const P& p)
{
s->total += p.second;
...
}
...
};
使用這種方法, for_each
復制p
都沒有關系,因為該副本將指向與原始對象相同的Storage對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.