【问题标题】:Getting errors trying to implement an operator<<?尝试实现 operator<<?
【发布时间】:2013-09-14 22:22:40
【问题描述】:

我是 C++ 新手,但仍在尝试使用构造函数等来掌握类实现。

我有一个程序分成3个文件,一个头文件,一个类实现文件,和驱动文件。

在头文件中,我收到错误“这行代码友元运算符

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

在我的驱动程序文件中,我收到一个错误“无法确定该代码的实例重载函数 '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;
}

【问题讨论】:

  • 你没有遵守三原则。

标签: c++


【解决方案1】:

你离开了返回类型:

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

【讨论】:

  • 是的,这就是问题,现在它已经完美了,谢谢,有点尴尬,但是哦,好吧。
  • @jim 远非完美,请参阅 chris 的评论:您的代码违反了三规则,因此包含错误。
【解决方案2】:

正如卡尔·诺鲁姆在他的解决方案中提到的那样

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;
    }

【讨论】:

  • 不,你可以把inline留在那里就好了。
  • 但是当我执行代码时出现错误 Error 1 error LNK2019: unresolved external symbol "public: __thiscall ARRAY::~ARRAY(void)" (??1ARRAY@@QAE@XZ) 引用在函数 _main
猜你喜欢
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
  • 2019-04-16
  • 1970-01-01
  • 2010-11-05
  • 2012-08-14
相关资源
最近更新 更多