我是c ++的新手,试图了解名称空间和类。 我这里有2个课程两个都在不同的文件中。
第一个是
#include<iostream>
using namespace std;
namespace project{
class Student{
string name,address,enrolmentDate ,usn;
int hours;
public:
Student(char* nusn, char* nname, char* naddress, char* ndate,int nhours){
usn = nusn;
name = nname;
address = naddress;
enrolmentDate = ndate;
hours = nhours;
}
Student(){
getData();
}
void getData(){
std::cout << "Enter Usn,Name,Address,EnrolmentDate,Hours\n";
std::cin >> usn >> name >> address >> enrolmentDate >> hours;
}
string getName(){
return name;
}
string getAddress(){
return address;
}
string getenrolmentDate(){
return enrolmentDate;
}
int getHours(){
return hours;
}
string getUsn(){
return usn;
}
};
}
第二课是
#include<iostream>
using namespace std;
namespace project{
class CourseRegistration{
string usn, courseId ;
int hours, grade;
public:
CourseRegistration(project::Student obj, string courseId, int nhours, int ngrade){
usn = obj.getUsn();
this->courseId = courseId;
hours = nhours;
grade = ngrade;
}
};
}
First class Compiles fine.But第二个类给出错误 错误就在学生对象附近。
Course.cpp:10:38: error: expected ‘)’ before ‘obj’
CourseRegistration(project::Student obj, string courseId, int nhours, int ngrade){
我如何纠正它?
答案 0 :(得分:1)
我没有看到任何证据表明您在第二个文件中包含了Student
的定义。您的类应在头(.h)文件中声明,并在源(.cpp)文件中实现。您的编译器可能会抱怨,因为它不知道Student
是一个类。
<强> Student.h 强>
#include<iostream>
using namespace std;
namespace project {
class Student {
private:
string name,address,enrolmentDate, usn;
int hours;
public:
Student( char*, char*, char*, char*, int );
Student();
void getData();
string getName();
string getAddress();
string getenrolmentDate();
int getHours();
string getUsn();
}
}
<强> Student.cpp 强>
#include "Student.h"
namespace project {
Student::Student( char* nusn, char* nname, char* naddress, char* ndate,int nhours ) {
usn = nusn;
name = nname;
address = naddress;
enrolmentDate = ndate;
hours = nhours;
}
Student() {
getData();
}
void getData() {
std::cout << "Enter Usn,Name,Address,EnrolmentDate,Hours\n";
std::cin >> usn >> name >> address >> enrolmentDate >> hours;
}
string getName() {
return name;
}
string getAddress() {
return address;
}
string getenrolmentDate() {
return enrolmentDate;
}
int getHours() {
return hours;
}
string getUsn() {
return usn;
}
}
<强> CourseRegistration.h 强>
#include "Student.h"
#include<iostream>
using namespace std;
namespace project{
class CourseRegistration {
private:
string usn, courseId ;
int hours, grade;
public:
CourseRegistration( Student, string, int, int );
}
}
<强> CourseRegistration.cpp 强>
#include<CourseRegistration.h>
namespace project {
CourseRegistration::CourseRegistration( Student obj, string courseId, int nhours, int ngrade ) {
usn = obj.getUsn();
this->courseId = courseId;
hours = nhours;
grade = ngrade;
}
}