2016-03-04 26 views
0

我正在學習有關超載的,我已經得到了好奇,如果我可以使重載運算符與兩個非類參數超載。C++運算符與兩個非類參數(有代理解決)

例如具有x和y矢量類調用

vector += (4.5, -2.1); 

謝謝!

編輯

我已經成功地做到這一點,也擴大采取的用戶創造儘可能多的參數。這是它的樣子:

//Point.hpp 
class Point 
{ 
friend class Proxy; 

private: 
double *val; 
int i; 
int amount; 

public: 
Point(); 
Point(const int&); 
void Set(const int &); 
double Get(const int &); 
int Amount(); 
Proxy operator += (const double &add); 
}; 

class Proxy 
{ 
private: 
int &i; 
Point &temp_point; 

public: 
Proxy operator , (const double&); 
Proxy(Point2D &, int&); 
}; 


//Point.cpp 
Point::Point() 
{ 
    this->amount = 2; 
    val = new double[this->amount]; 
    val[0] = 0; 
    val[1] = 0; 
}; 

Point::Point(const int &amount) : amount(amount) 
{ 
    val = new double[amount]; 
    for (int i = 0; i < amount; i++) 
    { 
     val[i] = 0; 
    } 
}; 

void Point::Set(const int &nr) 
{ 
    do 
    { 
     std::cout << "Give me value of " << nr << " coordinate: "; 
     std::cin.clear(); 
     std::cin.sync(); 
     std::cin >> val[nr]; 

     if (std::cin.fail()) 
     { 
      std::cout << "Try again, not acceptable...\n"; 
     } 
    } while (std::cin.fail()); 
} 
double Point::Get(const int &nr) 
{ 
    return val[nr]; 
} 

int Point::Amount() 
{ 
    return this->amount; 
} 
Proxy Point::operator += (const double &add) 
{ 
    this->i = 0; 
    this->val[i++] += add; 
    return Proxy(*this, i); 
} 
Proxy::Proxy(Point &point, int &i) : temp_point(point), i(i) 
{} 
Proxy Proxy::operator , (const double &value) 
{ 
    temp_point.val[i++] += value; 
    return Proxy(temp_point, i); 
} 

//Source.cpp example 
int main() 
{ 
    Point example(3); 

example += 4.5, -2.3, 3.0; 

for (int i = 0; i < example.Amount(); i++) 
    { 
     std::cout << example.Get(i) << " "; 
    } 
    std::cout << std::endl; 

    system("PAUSE"); 
    return 0; 
} 

希望有人覺得它有用。

回答

3

這是行不通的,因爲(4.5, -2.1)將調用內置的逗號操作,並簡單地計算爲-2.1。它有可能做到這一點:

vector += 4.5, -2.1; 

這工作,因爲,+=優先級低。您可以重載+=,以便它返回一個代理對象,該代理對象又會有一個超載的,運算符,該運算符將附加其他元素。

+1

或者你可以只是做'myVector.insert(myVector.end(){4.5 ,-2.1});'好吧,它更冗長,但至少它是內置的! –

+1

這將是可能的*除非*您必須提交您的代碼進行審查。 – rici

+0

謝謝,看起來很有趣。請您舉個例子,請稍等一會兒? – roman12356

0

如果你有對的載體,更可讀的辦法是

vector += std::make_pair(4.5, -2.1); 

看起來不夠神奇,這通常是一件好事。

1

你可以使用一個std::initializer_list

v & operator += (std::initializer_list<int> l) 
{ 
    sum = std::accumulate(l.begin(), l.end(), sum); 
    ..... 

你必須要你的電話sligthly改變

vector += {1 , 2};