尝试实现简单的getter和setter函数,但编译器说当我运行getters / setter时我的变量没有在范围中定义。 所以我添加了Course :: getID()因为也许我无法访问它们的原因是因为它们被设置为私有。但后来它说原型不匹配。那么我去了头文件并更改了类似于CPP文件的原型。然后它给了我错误:额外的资格'课程::'在成员getID();任何建议?
HEADER FILE
#ifndef COURSE_H
#define COURSE_H
#include <iostream>
#include <string.h>
const unsigned CourseNameSize = 10;
class Course {
public:
Course();
Course( const char * nam, char ID, unsigned cred );
char getName() const;
char getID() const;
unsigned GetCredits() const;
void setName( char name );
void SetCredits( unsigned cred );
void setID( char ID );
friend std::ostream & operator <<( std::ostream & os, const Course & C );
friend std::istream & operator >>( std::istream & input, Course & C );
private:
char name[CourseNameSize];
char ID;
int credits;
};
inline unsigned Course::GetCredits() const
{
return credits;
}
inline void Course::SetCredits( unsigned cred )
{
credits = cred;
}
CPP文件
#include "course.h"
using namespace std;
Course::Course()
{
name[0] = '\0'; // it is a char * string, not a C++ string object.
}
Course::Course( const char * nam, char ID,
unsigned cred )
{
strncpy( name, nam, CourseNameSize );
ID = ID;
credits = cred;
}
istream & operator >>( istream & input, Course & C )
{
input >> C.name >> C.ID >> C.credits;
return input;
}
ostream & operator <<( ostream & os, const Course & C )
{
os << " Course: " << C.name << '\n'
<< " ID: " << C.ID << '\n'
<< " Credits: " << C.credits << '\n';
return os;
}
void setID(char ID) {ID =ID;}
char getID() {return ID;}
void setName(char name) {name = name;}
char getName() {return name;}
void setCredits(int credits) {credits = credits;}
int getCredits() { return credits;}
答案 0 :(得分:4)
这让你的程序搞砸了:
ID = ID;
name = name;
credits = credits;
你可能应该写
this->ID = ID;
this->name = name;
this->credits = credits;
在你的cpp文件中,由于getID()
之类的函数是类成员,因此定义它们的正确方法是:
void Course::setID(char ID) { this_>ID = ID; }
char Course::getID() const { return this->ID; }
// ^^^^^
不要错过函数定义中的const
说明符。这使得功能不同。
由于您正在使用类std::istream
和std::ostream
(及其方法),因此您需要在cpp文件中包含相关标头:
<强> course.cpp 强>:
#include <iostream>
#include "course.h"
using namespace std;