簡體   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