Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何通过重载运算符拆分标头和实现_C++_Operator Overloading - Fatal编程技术网

C++ 如何通过重载运算符拆分标头和实现

C++ 如何通过重载运算符拆分标头和实现,c++,operator-overloading,C++,Operator Overloading,我从java世界学习C++作为一名中级开发人员 现在我正在尝试学习如何执行操作符重载 即使我在网上搜索了很多,所以: 这是我的参考: 下面是一个例子: // overload_date.cpp // compile with: /EHsc #include <iostream> using namespace std; class Date { int mo, da, yr; public: Date(int m, int d, i

我从java世界学习C++作为一名中级开发人员

现在我正在尝试学习如何执行操作符重载

即使我在网上搜索了很多,所以:

这是我的参考:

下面是一个例子:

// 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;  
}  
//重载\u date.cpp
//使用:/EHsc编译
#包括
使用名称空间std;
上课日期
{  
内莫,达,年;
公众:
日期(整数m、整数d、整数y)
{  
mo=m;da=d;yr=y;
}  

friend ostream&operator让代码编译的两件事:

第一: 你的getter应该是const

unsigned int Getx() const;
unsigned int Gety() const;

unsigned int Point::Getx() const
{
   return x;
}

unsigned int Point::Gety() const
{
   return y;
}
第二:

更正重写方法的返回:

return out << "A(" << a.Getx() << ", " << a.Gety() << ")";

返回
Getx()
Gety()
应该是
const
事实上,任何可以是
const
的东西都应该是
const
。但是它们不再是getter了……为什么?getter应该始终是const,因为它不会修改对象,setter会修改对象。为什么析构函数
是虚拟的
?您的getter和setter保护什么类不变量?没有为什么你不使用java语言,你不需要用C++语法编写Java,你会得到坏代码。C++ C++学习一种新的语言,而不是盲目地尝试将其他语言的原理应用到C++中。
unsigned int Getx() const;
unsigned int Gety() const;

unsigned int Point::Getx() const
{
   return x;
}

unsigned int Point::Gety() const
{
   return y;
}
return out << "A(" << a.Getx() << ", " << a.Gety() << ")";