本质上,我的计算机科学老师让我使用朋友std :: ostream方法进行输出。如下所示,我已将其导入头文件中,但是我不知道如何在student.cpp中使用它。添加Student :: ostream无效。我将如何在student.cpp中使用标头预定义方法
我的头文件
#pragma once
#include <iostream>
class student
{
public:
student();
std::string settingStudentName;
bool disiplineIssue();
// provided again so you learn this valuable override method for printing class data.
friend std::ostream& operator << (std::ostream& const student &);
private:
std::string studentName;
bool hasDisciplineIssue;
};
学生.cpp
#include "student.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
student::student()
{
}
bool student::disiplineIssue()
{
// Max the random integer can go
int max = 100;
srand(time(0));
int random = rand()%max;
// bool variable for returning
bool True_or_False = false;
if (random <= 5)
{
True_or_False = true;
}
return True_or_False;
}
ostream& operator<< (ostream& output, const student& aStudent) {
output << aStudent.studentName << " ";
if (aStudent.hasDisciplineIssue) {
output << "has ";
}
else {
output << "doesn't have ";
}
output << "a discipline issue";
return output;
}
编辑:当我前面没有student ::时,ostream可以工作,但是如果我在前面添加student :::它表示无法解析该符号。我不确定没有学生的那一个::是否正在使用我在头文件中定义的那个。
我将以以下方式进行:
settingStudentName
在头文件和主文件中起作用;#include
);main()
驱动程序功能;friend std::ostream& operator << (std::ostream&, const student &);
)缺少,
函数参数之间的逗号分隔符。MWE:
#ifndef STUDENT_H_INCLUDED
#define STUDENT_H_INCLUDED
#include <iostream>
#include <string>
class student
{
public:
student();
std::string settingStudentName(const std::string&);
bool disiplineIssue();
// provided again so you learn this valuable override method for printing class data.
friend std::ostream& operator << (std::ostream&, const student &);
private:
std::string studentName;
bool hasDisciplineIssue;
};
#endif // STUDENT_H_INCLUDED
#include "student.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
student::student()
{
}
string student::settingStudentName(const string& input)
{
studentName = input;
return input;
}
bool student::disiplineIssue()
{
// Max the random integer can go
int max = 100;
srand(time(0));
int random = rand()%max;
// bool variable for returning
bool True_or_False = false;
if (random <= 5)
{
True_or_False = true;
}
return True_or_False;
}
ostream& operator<< (ostream& output, const student& aStudent) {
output << aStudent.studentName << " ";
if (aStudent.hasDisciplineIssue) {
output << "has ";
}
else {
output << "doesn't have ";
}
output << "a discipline issue";
return output;
}
int main()
{
student Jack;
Jack.settingStudentName("Jack");
Jack.disiplineIssue();
cout << Jack << endl;
return 0;
}
这是输出:
Jack has a discipline issue
这是您可以使用https://wandbox.org/permlink/mF49xQxkXs3M7n0M播放的编译版本
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句