C++ 在C++;
每次我运行代码编译器时,都会给出对象已经定义的错误,我不知道我在整个代码中犯了什么错误 即使我在一个文件中完成了这一切,它仍然可以工作,但我不知道为什么它不能以这种方式工作。任何人都可以帮助我,我在代码中犯了什么错误 任何帮助都将不胜感激。 多谢各位 student.hC++ 在C++;,c++,filesystems,perl-data-structures,C++,Filesystems,Perl Data Structures,每次我运行代码编译器时,都会给出对象已经定义的错误,我不知道我在整个代码中犯了什么错误 即使我在一个文件中完成了这一切,它仍然可以工作,但我不知道为什么它不能以这种方式工作。任何人都可以帮助我,我在代码中犯了什么错误 任何帮助都将不胜感激。 多谢各位 student.h ifndef STUDENT define STUDENT class Student { public: char student_no[10]; char student_name[20]; ch
ifndef STUDENT
define STUDENT
class Student
{
public:
char student_no[10];
char student_name[20];
char student_address[20];
char student_score[20];
Student();
};
Student::Student()
{//constructor
student_no[0] = 0; student_name[0] = 0; student_address[0] = 0;
student_score[0] = 0;
}
#endif
student.cpp
using namespace std;
#include "writestr.cpp"
#include <fstream>
#include <string.h>
#include <iostream>
int main(){
char filename[20];
Student s;
cout << "Enter the file name:" << flush;
cin.getline(filename, 19);
ofstream stream(filename, ios::out);
if (stream.fail()) {
cout << "File open failed!" << endl;
return 0;
}
while (1) {
cin >> s; // read fields of person
if (strlen(s.student_name) == 0) break;
// write person to output stream
stream << s; // write fields of person
}
return 1;
}
using namespace std;
#include "readper.cpp"
#include <fstream>
#include <string.h>
#include <iostream>
ostream & operator << (ostream & stream, Student & s)
{ // insert fields into file
stream << s.student_name << s.student_no << s.student_address
<< s.student_score;
return stream;
}
using namespace std;
#include "student.h"
#include <fstream>
#include <string.h>
#include <iostream>
istream & operator >> (istream & stream, Student & s)
{ // read fields from input
cout << "Enter Student Name, or <cr> to end: " << flush;
stream.getline(s.student_name, 30);
if (strlen(s.student_name) == 0) return stream;
cout << "Enter Student Name: " << flush; stream.getline(s.student_name, 30);
cout << "Enter Student Id Number: " << flush; stream.getline(s.student_no, 30);
cout << "Enter Address: " << flush; stream.getline(s.student_address, 30);
cout << "Enter Score: " << flush; stream.getline(s.student_score, 15);
return stream;
}
使用名称空间std;
#包括“writest.cpp”
#包括
#包括
#包括
int main(){
字符文件名[20];
学生证;
cout您正在头文件中定义(而不仅仅是声明)构造函数:
Student::Student()
{//constructor
student_no[0] = 0; student_name[0] = 0; student_address[0] = 0;
student_score[0] = 0;
}
这会在包含头文件的每个cpp中反复定义构造函数(生成代码)。由于此定义没有inline
关键字,因此它可能在程序中只存在一次,而不是多次。在多个翻译单元(cpp文件)中定义非inline构造函数会导致错误
可能的解决办法:
将构造函数定义移动到类中,或
以inline
关键字作为前缀,或
将其移动到其中一个cpp文件
另一个问题:您包括cpp文件,这会通过一次又一次地声明相同的内容而导致更多问题。只需将它们添加到project/makefile/etc,而不是包括:
#include "writestr.cpp"
当询问有关生成错误的问题时,首先创建一个显示给我们的。然后复制粘贴(作为文本)所示示例中完整的生成日志。并且在错误所在的代码行中包含注释。请阅读,以及。顺便说一句,您的重载“输入”操作员<代码> >代码>不应该输出任何东西。如果你试图用文件或字符串流来代替它,而不是<代码> STD::CIN < /代码>,那么程序的用户不应该输入任何东西,输出都是错误的。永远不包括你使用的C++版本的CPP文件吗?如果你使用最新的一个,你可以直接初始化。在Student
class中声明时对班级成员进行加密。