我正在努力保持我的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;
这就是我收到操作员错误的地方。奇怪的是,如果我注释掉重载的运算符并将其保留在students.cpp中,它会编译find。
#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
}
并且,导致错误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;
}
这是我得到的错误
语法错误:缺少';'在'&amp;'之前 :错误C2433:'ostream':'朋友'不允许数据声明
错误C4430:缺少类型说明符 - 假定为int。注意:C ++不支持default-int
错误C2061:语法错误:标识符'ostream'
错误C4430:缺少类型说明符 - 假定为int。注意:C ++不支持default-int
错误C2805:二进制'运算符&lt;&lt;'参数太少了 1&gt;生成代码...
1 GT;编译...
1&gt; students.cpp
我的眼睛在燃烧,我无法弄清楚为什么它对重载的操作员感到不满......
答案 0 :(得分:6)
您正在使用ostream
而未使用命名空间std::
编译器错误/警告模糊地告诉你它遇到了尚未声明的类型。
friend std::ostream& operator << (std::ostream& out,const students& student);
答案 1 :(得分:0)
如果您的目标是提高您的C ++知识,请参阅sbi的评论:
现在,专门查看您的代码: 我会假设
cout << "\noriginal data set -- " << *students;
是一个拼写错误,学生是一个类型,你只能取消引用一个指针,这不是(至少在你发布的代码片段中 - 如果没有,请仔细考虑变量名字!)。 2.据推测,你的意思是
cout << "\noriginal data set -- " << *classmates;
如果是这样,检查你的流操作符是否正确实现了quack。