操作员超载

1 c++ operator-overloading

我正在研究这个项目,试图保持我的c ++知识.无论如何,当我尝试实现运算符重载时,我遇到了很多很多错误.不知道为什么.

#include "students.h"
#include <iostream>
#include "Quack.h"

using namespace std;

void main()
{


quack* classmates = new quack;

classmates->pushFront(students("corey", "9081923456", 4.0));

cout << "\noriginal data set -- " << *students;
Run Code Online (Sandbox Code Playgroud)

这就是我得到操作员错误的地方.奇怪的是,如果我注释掉重载的运算符并将其保留在students.cpp中,它会编译查找.

#ifndef STUDENTS_H
#define STUDENTS_H
#include <iostream>

class students
{
      // causing errors
friend ostream& operator << (ostream& out,const students& student);

public:
students();
students(char * name, char* oitId, float gpa);
students(const students& student); // copy constructor;
 ~students();
const students& operator=(const students& student);

void getName(char* name) const;
void getoitId(char* oitId) const;
float getGpa(void) const;

void setName(char* name);
void setoitId(char* oitId);
void setGpa(float gpa);


private:
char*    name;
char*    oitId;
float    gpa;

};

#endif

}
Run Code Online (Sandbox Code Playgroud)

并且,导致错误alo.但不是它本身..

#include "students.h"
#include <iostream>
#include <iomanip>

using namespace std;
#pragma warning(disable:4996)       

private:
char* name;
char* oitId;
float gpa;

students::students(): name(NULL), oitId(NULL), gpa(0)
{
}


students::students(char *name, char *oitId, float gpa): name(NULL), oitId(NULL), gpa(0)
{
setName(name);
setoitId(oitId);

}

students::~students()
{

if(name)
delete[] name;
if(oitId)
delete[] oitId;

}




const students& students::operator=(const students& student)
{

//if it is a self copy, don't do anything
if(this == &student)
    return *this;
//make current object *this a copy of the passed in student
else
{
    setName(student.name);
    setoitId(student.oitId);
    //setGpa(student.gpa);
    return *this;
}

}


void students::setName(char *name)
{

//release the exisisting memory if there is any
if(this->name)
delete [] this->name;

//set new name
this->name = new char[strlen(name)+1];
strcpy(this->name, name);

}

void students::setoitId(char *oitId)
{

if(this->oitId)
delete [] this->oitId;

//set new Id
this->oitId = new char[strlen(oitId)+1];
strcpy(this->oitId, oitId);

}

ostream& operator<< (ostream& out, const students& student)
{

//out << setw(20) << student.name
    //<< setw(15) << student.pccId
    //<< setw(8) << fixed << setprecision(2) << student.gpa;
return out;
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

语法错误:缺少';' 在'&'之前
:错误C2433:'ostream':'朋友'不允许数据声明
错误C4430:缺少类型说明符 - 假定为int.注意:C++不支持default-int
错误C2061:语法错误:标识符'ostream'
错误C4430:缺少类型说明符 - 假定为int.注意:C++不支持default-int
错误C2805:二进制'operator <<'参数太少
1>生成代码...
1>编译...
1> students.cpp

我的眼睛在燃烧,我无法弄清楚为什么它对重载的操作员不满意..

wkl*_*wkl 6

您正在使用ostream而不使用命名空间限定它std::

编译器错误/警告模糊地告诉您它遇到了尚未声明的类型.

friend std::ostream& operator << (std::ostream& out,const students& student);
Run Code Online (Sandbox Code Playgroud)