C++:运算符重载
c++ : operator overloading
我设计了与std::pair
非常相似的简单结构。
struct pii{
int first;
int second;
pii (int _first=-1, int _second=-1)
: first(_first), second(_second) {}
//
pii& operator=(const pii &ref){
first=ref.first;
second=ref.second;
return *this;
}
pii operator+(const pii &ref){
return pii(first+ref.first, second+ref.second);
}
//
bool operator<(pii &ref){
if(first<ref.first && second<ref.second)
return true;
return false;
}
bool operator>(pii &ref){
return ref>(*this);
}
bool operator<=(pii &ref){
return !((*this)>ref);
}
bool operator>=(pii &ref){
return !((*this)<ref);
}
//
bool operator==(pii &ref){
if(first==ref.first && second==ref.second)
return true;
return false;
}
bool operator!=(pii &ref){
return !((*this)==ref);
}
};
假设有两个pii
对象。我想使用比较操作(<
,>
,<=
,>=
,==
,!=
(转换以下句子。
pii one, another;
// I want to convert the below sentence.
if(one.first<=another.first && one.second<=another.second)
if(one<=another)
//这不是正确的答案。
可以转换吗?那么,答案是什么?
这应该是比较第一个和第二个变量的正确代码:
bool operator<(pii &ref){
return first<ref.first && second<ref.second;
}
bool operator>(pii &ref){
return first>ref.first && second>ref.second;
}
bool operator<=(pii &ref){
return first<=ref.first && second<=ref.second;
}
bool operator>=(pii &ref){
return first>=ref.first && second>=ref.second;
}
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用