我正在學習有關超載的,我已經得到了好奇,如果我可以使重載運算符與兩個非類參數超載。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;
}
希望有人覺得它有用。
或者你可以只是做'myVector.insert(myVector.end(){4.5 ,-2.1});'好吧,它更冗長,但至少它是內置的! –
這將是可能的*除非*您必須提交您的代碼進行審查。 – rici
謝謝,看起來很有趣。請您舉個例子,請稍等一會兒? – roman12356