繁体   English   中英

尝试实现运算符时出现错误<<?

[英]Getting errors trying to implement an operator<<?

我是c ++的新手,仍然尝试通过构造函数等来掌握类的实现。

我有一个程序,该程序分为3个文件:标头文件,类实现文件和驱动程序文件。

在头文件中,我收到一条错误消息“此行代码的朋友运算符<<(ostream&,ARRAY&);缺少显式类型(假定为'int');

在我的类实现文件中,我收到此朋友函数的错误,说我无权访问私有成员。

在我的驱动程序文件中,此代码出现错误“无法确定哪个实例重载了功能'endl'”:cout <

我将在下面留下一些代码,首先是.h文件,然后是类实现文件,然后是驱动程序文件。 非常感谢您为清除此问题提供的任何帮助。

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

class ARRAY
{
public:

    ARRAY();

    ARRAY(int );

    ARRAY(const ARRAY &);
    ~ARRAY();

    friend operator<<(ostream &, ARRAY &);

private:

    string *DB;

    int count;

    int capacity;
};

实施文件

#include "array.h"

ARRAY::ARRAY()
{
    cout<<"Default Constructor has been called\n";

    count = 0;
    capacity = 2;

    DB = new string[capacity];
}

ARRAY::ARRAY(int no_of_cells)
{
    cout<<"Explicit-Value Constructor has been called\n";

    count = 0;
    capacity = no_of_cells;

    DB = new string[capacity];
}

ARRAY::ARRAY(const ARRAY & Original)
{
    cout<<"The copy constructor has been invoked\n";
    count = Original.count;
    capacity = Original.capacity;

    DB = new string[capacity];

    for(int i=0; i<count; i++)
    {
        DB[i] =Original.DB[i];
    }

}

inline ARRAY::~ARRAY()
{

    cout<<"Destructor Called\n";
    delete [ ] DB;
}

ostream & operator<<(ostream & out, ARRAY & Original)
{
    for(int i=0; i< Original.count; i++)
    {
        out<<"DB[" << i <<"] = "<< Original.DB[i]<<endl;
    }
    return out;
}

驱动档案

#include <iostream>
#include <string>
#include "array.h"
using namespace std;

int main()
{
    cout<<"invoking the default constructor (11)"<<endl;
    ARRAY myArray;
    cout<<"Output after default constructor called\n";
    cout<<myArray<<endl<<endl;

    cout<<"invoking the explicit-value constructor (12)"<<endl;
    ARRAY yourArray(5);
    cout<<"Output after explicit-value constructor called\n";
    //cout<<yourArray<<endl<<endl;


    cout<<"invoking the copy constructor (3)"<<endl;
    ARRAY ourArray = myArray;
    cout<<"Output after copyconstructor called\n";
    cout<<ourArray<<endl<<endl;

        return 0;
}

您放弃了返回类型:

friend ostream& operator<<(ostream &, ARRAY &);

正如卡尔·诺鲁姆(Carl Norum)在解决方案中提到的

You left off the return type:

friend ostream& operator<<(ostream &, ARRAY &);

你也有删除inline

inline ARRAY::~ARRAY()
{

    cout<<"Destructor Called\n";
    delete [ ] DB;
}

成为

ARRAY::~ARRAY()
    {

        cout<<"Destructor Called\n";
        delete [ ] DB;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM