Sha*_*ode 2 c++ overloading vector operator-overloading
我试图找到一个简单的示例程序,它重载数学向量的以下运算符.
Constructor // create
= (equals) // assign
+; -; +=; -= // add sub
*; /; *=; /= // multi divide
++; -- // plus minus
== // compare
>; >=
<; <=
[] // access a value
Run Code Online (Sandbox Code Playgroud)
似乎找不到任何好的简单教程.我强调这很简单,因为我现在只学习这些东西.如果有人可以链接我,或者甚至更好地为一个操作员编程一个简单的重载,作为一个例子是不可思议的!
编写运算符时需要了解一些事项,而这些运算符并不常用于其他函数.
例如,赋值运算符将return *this因为您更改向量的值:
class v {
public:
double x_, y_;
v& operator += (const v& rhs)
{
_x += rhs._x;
_y += rhs._y;
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
另一个有趣的,前置++和后置++只是因为一个未使用的参数不同:
class v {
public:
double x_, y_;
v& operator ++ (); // ++v
v& operator ++ (int); // v++
};
Run Code Online (Sandbox Code Playgroud)
"相等"(赋值)是另一个在使用指针时很棘手的.对于向量,它通常不会有问题,但如果您定义向量V并将其分配给自身,则必须小心:
class v {
public:
double x_, y_;
v& operator = (const v& rhs)
{
if(this != &rhs)
{
x_ = rhs.x_;
y_ = rhs.y_;
}
}
};
Run Code Online (Sandbox Code Playgroud)
在你的情况下,if()意志肯定没有用,但想想做这样的事情:
delete p_;
p_ = new foo;
p_->x_ = rhs.p_->x_;
Run Code Online (Sandbox Code Playgroud)
如果&rhs == this,那么delete p_删除rhs指针!这意味着在第3行访问它是一个错误.
其余的应该很容易使用.比较运算符返回bool并且是const:
class v {
public:
double x_, y_;
bool operator == (const v& rhs) const
{
return x_ == rhs.x_ && y_ == rhs.y_;
}
};
Run Code Online (Sandbox Code Playgroud)
除了[]运营商.该版本有两个版本:
class v {
public:
// I would imagine you'd use an array but as a simple example...
double x_, y_;
double operator [] (int idx) const
{
return idx == 0 ? x_ : y_;
}
v_ref operator [] (int idx)
{
v_ref v(this, idx);
return r;
}
};
Run Code Online (Sandbox Code Playgroud)
如您所见,[]运算符的非常量版本返回引用.这是必要的,所以你可以这样写:
r[3] = 7.3;
Run Code Online (Sandbox Code Playgroud)
r[3]返回该引用,然后使用7.3参数调用引用的赋值.
class v_ref
{
public:
v *p_;
int i_;
v_ref(v *p, int i)
: p_(p), i_(i)
{
}
operator = (double q)
{
// again, I suppose you'd use an array instead!
if(i_ == 0)
{
p_->x_ = q;
}
else
{
p_->y_ = q;
}
}
};
Run Code Online (Sandbox Code Playgroud)
假设你想要一些安全性,矢量指针可以使用一个引用计数器,这样你就可以知道主矢量对象是否在它的所有引用对象之前被删除了......
另一个注意事项:我想你的构造函数将分配一个double数组(或使用一个std::vector<double>类型......)如果你使用new,记得在析构函数中删除,并且当if()赋值运算符非常重要时.
| 归档时间: |
|
| 查看次数: |
13071 次 |
| 最近记录: |