C++ & Java - 重载运算符
C++ & Java - overloading operator
我很难理解C++和Java中重载运算符的主题。
例如,我定义了一个新的类Fraction:
class Fraction {
public:
Fraction (int top, int bottom) { t = top; b = bottom; }
int numerator() { return t; }
int denominator() { return b; }
private:
int t, b;
};
并且我想要重载运算符CCD_ 1以打印Fraction。我是怎么做的?我需要在类分数内还是在类分数外过载?
在java中,是否可以重载运算符?如何在那里执行(例如,我想重载运算符+
)。
如果这个题目有度量衡的话,那就太好了。
在java中,是否可以重载运算符?
不,Java没有运算符重载。
对于C++:重载<lt;msdn 上的操作员
// overload_date.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class Date
{
int mo, da, yr;
public:
Date(int m, int d, int y)
{
mo = m; da = d; yr = y;
}
friend ostream& operator<<(ostream& os, const Date& dt);
};
ostream& operator<<(ostream& os, const Date& dt)
{
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}
int main()
{
Date dt(5, 6, 92);
cout << dt;
}
所以,作为"我需要在类分数内或类分数外重载它?"的答案您将函数声明为类的friend
,以便std::osteam
对象可以访问其私有数据。但是,函数是在类之外定义的。
为了给你一个由我自己提供的完整答案,Marcelo和David Rodríguez-dribeas在评论中说道:
在Java中,不能重载运算符
完成我的答案:
[…],但是+和+=运算符字符串的默认重载串联。这是唯一的例外
nbsp nbsp nbsp nbsp@Marcelo
关于C++重载运算符:
对于C++方面,看看这个问题:stackoverflow.com/questions/4421706/运算符重载
nbsp nbsp nbsp nbsp@David Rodríguez-dribeas
在c++中,您可以为应用它的类重载一个运算符
class Fraction {
public:
Fraction (int top, int bottom) { t = top; b = bottom; }
int numerator() { return t; }
int denominator() { return b; }
inline bool operator << (const Fraction &f) const
{
// do your stuff here
}
private:
int t, b;
};
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用