我重载了一个cout和cin opeartor,当我尝试使用它时,它给了我一个像这样的错误:
1 IntelliSense: function "std::basic_ostream<_Elem, _Traits>::basic_ostream(const std::basic_ostream<_Elem, _Traits>::_Myt &)
[with _Elem=char, _Traits=std::char_traits<char>]"
(declared at line 84 of "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\ostream") cannot be referenced -- it is a deleted function
Run Code Online (Sandbox Code Playgroud)
这是我班级的头文件:
#pragma once
#include <iostream>
class Point2D
{
private:
int m_X;
int m_Y;
public:
Point2D(): m_X(0), m_Y(0)
{
}
Point2D(int x, int y): m_X(x), m_Y(y)
{
}
friend std::ostream& operator<< (std::ostream out, const Point2D &point)
{
out << "(" << point.m_X << "," << point.m_Y << ")" << std::endl;
return out;
}
friend std::istream& operator>> (std::istream in, Point2D &point)
{
in >> point.m_X;
in >> point.m_Y;
return in;
}
int getX() const { return m_X; }
int getY() const { return m_Y; }
~Point2D();
};
Run Code Online (Sandbox Code Playgroud)
所以,基本上,它只是一个可以返回并设置X和Y坐标的类.我覆盖<<
和>>
操作员使事情变得更容易.
但是当我尝试在主函数中使用它时,如下所示:
#include "stdafx.h"
#include <iostream>
#include "Point2D.h"
using namespace std;
int main(int argc, char * argv[])
{
Point2D point(7, 7);
cout << point; //there's an error here.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这一行似乎有错误:
cout << point;
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
错误消息显示ostream
无法复制.
friend std::ostream& operator<< (std::ostream out, const Point2D &point)
{
...
Run Code Online (Sandbox Code Playgroud)
std::ostream out
是值传递:当operator <<
调用时,编译器会尝试复制参数.但是,std::ostream
无法复制,因此编译失败.
你应该使用参考.
friend std::ostream& operator<< (std::ostream &out, const Point2D &point)
{
...
friend std::istream& operator>> (std::istream &in, Point2D &point)
{
...
Run Code Online (Sandbox Code Playgroud)
(即使你使用的是一些提供复制的类,你也不应该使用pass-by-val.复制一些对象是如此昂贵;)
归档时间: |
|
查看次数: |
1696 次 |
最近记录: |