[英]operator overload
我正在嘗試保持我的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
}
並引起錯誤。 但不是本身。
#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;
}
這是我得到的錯誤
語法錯誤:缺少';' 在“&”之前
:錯誤C2433:“ ostream”:數據聲明中不允許使用“ friend”
錯誤C4430:缺少類型說明符-假定為int。 注意:C ++不支持default-int
錯誤C2061:語法錯誤:標識符'ostream'
錯誤C4430:缺少類型說明符-假定為int。 注意:C ++不支持default-int
錯誤C2805:二進制“運算符<<”參數太少
1>正在生成代碼...
1>正在編譯...
1> students.cpp
我的眼睛發燙,我不知道為什么它對超負荷的操作員不滿意。
您正在使用ostream
而不使用名稱空間std::
編譯器錯誤/警告模糊地告訴您,它遇到了尚未聲明的類型。
friend std::ostream& operator << (std::ostream& out,const students& student);
如果您的目標是提高C ++知識,請與sbi的注釋保持一致:
現在,專門查看您的代碼:1.我假設
cout << "\noriginal data set -- " << *students;
是一個錯字, 學生是一個類型,您只能取消引用一個指針,但這不是(至少在您發布的代碼段中-否則,請仔細考慮變量名!)。 2.想必你是故意的
cout << "\noriginal data set -- " << *classmates;
如果是這樣,請檢查您的流運算符以確認Quack是否正確實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.