B.J*_*B.J 3 c++ overloading operator-overloading
尝试重载运算符时出现错误。
我的头文件:
#include<iostream>
#include<string>
using namespace std;
#ifndef HALLGATO_H
#define HALLGATO_H
class Hallgato {
private:
char* nev;
char* EHA;
int h_azon;
unsigned int kepesseg;
public:
friend ostream& operator<<(ostream& output, const Hallgato& H);
};
#endif
Run Code Online (Sandbox Code Playgroud)
我的cpp文件:
#include<iostream>
#include "Hallgato.h"
using namespace std;
ostream& Hallgato::operator<<(ostream& output, const Hallgato& H) {
output << "Nev: " << H.nev << " EHA: " << H.EHA << " Azonosito: " << H.h_azon << " Kepesseg: " << H.kepesseg << endl;
return output;
}
};
Run Code Online (Sandbox Code Playgroud)
在我的.cpp文件中,当我想定义重载的运算符时<<,出现错误。为什么?
运算符不是课程的成员,所以是朋友
ostream& Hallgato::operator<<(ostream& output, const Hallgato& H) {
Run Code Online (Sandbox Code Playgroud)
应该
ostream& operator<<(ostream& output, const Hallgato& H) {
Run Code Online (Sandbox Code Playgroud)
为了能够使用其他文件中的运算符,您还应该将原型添加到头文件中。
头文件将变成这个
哈尔加托
#ifndef HALLGATO_H
#define HALLGATO_H
#include<iostream>
#include<string>
class Hallgato {
private:
char* nev;
char* EHA;
int h_azon;
unsigned int kepesseg;
public:
friend std::ostream& operator<<(std::ostream& output, const Hallgato& H);
};
std::ostream& operator<<(std::ostream& output, const Hallgato& H);
#endif /* End of HALLGATO_H */
Run Code Online (Sandbox Code Playgroud)
您可以在“ .cpp”文件中的某个位置实现操作符功能,也可以在头文件中执行该功能,但随后必须经常使用某些编译器进行重新编译。
哈尔加托
#include "hallgato.h"
std::ostream& operator<<(std::ostream& output, const Hallgato& H)
{
/* Some operator logic here */
}
Run Code Online (Sandbox Code Playgroud)
注意:修改头文件时,许多编译器通常不会在.cpp文件中重新包含它们。这样做是为了避免不必要的重新编译。要强制重新包含,您必须对包含这些标头的源文件进行一些修改(删除空行),或在编译器/ IDE中强制重新编译。
| 归档时间: |
|
| 查看次数: |
6808 次 |
| 最近记录: |