Установить и получить методы в классе для объектов - PullRequest
0 голосов
/ 16 апреля 2020

У меня есть класс Result, который принимает два других класса UNIT и Date в качестве параметров объекта, так что я могу хранить в них значения для использования в этих классах. Я запишу то, что получил до сих пор, и некоторые из ошибок, которые я получаю, заключаются в следующем.

error: prototype for 'int Result::GetUnit() const' does not match any in class 'Result'|
lab2\Result.h|17|error: candidate is: Result Result::GetUnit() const|
lab2\Result.cpp|66|error: prototype for 'int Result::GetDate()' does not match any in class 'Result'|
lab2\Result.h|18|error: candidate is: Result Result::GetDate() const|
lab2\Result.cpp|73|error: 'SetResult' was not declared in this scope|
error: 'SetResult' was not declared in this scope|

Для ошибки not declared in this scope после исследования я понимаю, что мне нужно определить функции до того, как будет сделан первый вызов. Я сделал это в файле. cpp, но все равно получаю сообщение об ошибке. Что я делаю не так?

Result.h:

#ifndef RESULT_H
#define RESULT_H

#include <iostream>
#include <string>
#include "UNIT.h"
#include "Date.h"


//const unsigned ResultSize = 10;
using namespace std;
class Result
{
    public:
        Result(){};
        Result(UNIT unitobj1, unsigned marks1, Date dateobj1);
        Result GetUnit() const;
        Result GetDate() const;
        void SetDate(Date dateobj1);
        void SetUnit(UNIT unitonj1);
        void SetMarks( unsigned marks1 );
        unsigned GetMarks() const;

        void SetCredits( unsigned cred );
        unsigned GetCredits() const;

        string GetID() const;
        void SetID(string idd);


        void SetResult(istream & input);
        void GetResult(ostream & os);//unsigned GetUnit() const;


    private:

        UNIT unitobj;
        Date dateobj;
        string id;
        int credits;
        unsigned marks;

};
inline unsigned Result::GetCredits() const
{
  return credits;
}

ostream & operator <<( ostream & os, const Result & S);
istream & operator >>( istream & input, Result & S);

#endif // RESULT_H

Результат. cpp:

#include "Result.h"
#include "UNIT.h"
#include "Date.h"

Result::Result(UNIT unitobj1, unsigned marks1, Date dateobj1)
{

    unitobj = unitobj1;
    marks = marks1;
    dateobj = dateobj1;

}

void Result::SetResult(istream &input){

    UNIT unitobj1;
    unsigned marks1;
    Date date1;

    input >> unitobj1 >> marks1 >> date1;

    SetUnit(unitobj1);
    SetMarks(marks1);
    SetDate(date1);

}



void Result::GetResult(ostream &os){

    os << GetUnit() < "  Marks: " << GetMarks() << '\n' << GetDate() << '\n';

}

void Result::SetUnit(UNIT unitobj1){

    unitobj = unitobj1;

}

void Result::SetMarks(unsigned marks1){

    marks = marks1;

}

void Result::SetDate(Date dateobj1){

    dateobj = dateobj1;

}

Result::GetUnit() const{

    return unitobj;

}

inline unsigned Result::GetMarks() const{

    return marks;

}

Result::GetDate(){

    return dateobj;

}
istream & operator >>( istream & input, Result & S)
{
      SetResult(input);
      return input;

}

ostream & operator <<( ostream & os, const Result & S)
{
      GetResult(os);
      return os;
}

Date.h:

#if !defined(_DATE_H)
#define _DATE_H

#include <iostream>
#include <string>

using namespace std;

class Date {
public:
    Date();
    Date(unsigned day1, string month1, unsigned year1);

    void SetDay(unsigned day1);
    void SetMonth(string month1);
    void SetYear(unsigned year1);
    unsigned GetDay() const;
    string GetMonth() const;
    unsigned GetYear() const;

    void SetDate(istream &input);
    void GetDate(ostream & os);


private:

    unsigned day;
    string month;
    unsigned year;

};

 ostream & operator <<(ostream & os, const Date & D);
 istream & operator >>(istream & input, Date & D);
#endif  //_DATE_H

Дата. cpp:

//
//
//  Generated by StarUML(tm) C++ Add-In
#include "Date.h"

Date::Date(unsigned day1, string month1, unsigned year1) {

    day = day1;
    month = month1;
    year = year1;

}


void Date::SetDay(unsigned day1) {

    day = day1;

}

void Date::SetMonth(string month1) {

    month = month1;

}

void Date::SetYear(unsigned year1) {

    year = year1;

}

inline unsigned Date::GetDay() const {

    return day;

}

string Date::GetMonth() const {

    return month;

}

inline unsigned Date::GetYear() const {

    return year;

}
void Date::SetDate(istream &input){

    unsigned day1;
    string month1;
    unsigned year1;


    input >> day1 >> month1 >> year1;
    SetDay(day1);
    SetMonth(month1);
    SetYear(year1);

}

void Date::GetDate(ostream &os){

    os << "  Date: " << GetDay() << " " << GetMonth() << " " << GetYear();

}


istream & operator >>( istream & input, Date & D) {

    SetDate(input);
    return input;

}

ostream & operator <<( ostream & os, const Date & D) {

    GetDate(os);

    return os;

}

UNIT.h:

        #ifndef UNIT_H
        #define UNIT_H

        #include <iostream>
        #include <string>  // C string library

        using namespace std;



        const unsigned UnitNameSize = 10;

        class UNIT
        {
        public:
          UNIT();
          UNIT( string nam, string idd, unsigned cred);

          void SetName(string nam);
          string GetName() const;

          void SetMarks(unsigned marks1);
          unsigned GetMarks();

          void SetCredits(unsigned cred);
          unsigned GetCredits() const;

          string GetID() const;
          void SetID(string idd);

          void SetUnit(istream & input);
          void GetUnit(ostream & os);

        private:


          string name;  
          string id;   
          unsigned marks;
          int credits;
        };

        ostream & operator <<( ostream & os, const UNIT & U);
        istream & operator >>( istream & input, UNIT & U);



        #endif // UNIT_H

UNIT. cpp:

#include "UNIT.h"
#include <string>

UNIT::UNIT()
{
  name[0] = '\0';
}

void UNIT::SetName(string nam)
{
  name = nam;
}


string UNIT::GetName() const
{
  return name;
}

void UNIT::SetID(string idd)
{
  id = idd;
}


string UNIT::GetID() const
{
  return id;
}

void UNIT::SetCredits(unsigned cred){

    credits = cred;

}

inline unsigned UNIT::GetCredits() const{

    return credits;

}
UNIT::UNIT( string nam, string idd,
                unsigned cred)
{
  name.replace(0, 10, nam );
  id = idd;
  credits = cred;
}

void UNIT::SetUnit(istream &input){

  string nam;
  string idd;
  unsigned cred;

  getline(input,nam, '\n');
  getline(input,idd,'\n');
  input >> cred;

  SetName(nam);
  SetID(idd);
  SetCredits(cred);

}

void UNIT::GetUnit(ostream & os){

  os << "  Unit ID:  " << GetID() << '\n'
     << "  Unit Name: " << GetName() << '\n'
     << "  Credits: " << GetCredits() << '\n';

}


istream & operator >>( istream & input, UNIT & U)
{
  SetUnit(input);

  return input;
}

ostream & operator <<( ostream & os, const UNIT & U)
{
  GetUnit(os);
  return os;
}

Примечание: я знаю что я могу просто сделать перегруженные операторы методами класса и объявить их друзьями, но я пытаюсь добиться этого с помощью методов set и get. Любая помощь будет принята с благодарностью!

1 Ответ

3 голосов
/ 16 апреля 2020

Итак, это довольно просто, посмотрите на Result::GetUnit

Result::GetUnit() const {
    return unitobj;
}

В этом методе отсутствует тип возврата . Теперь посмотрите на unitobj

UNIT unitobj;

Итак, ясно, что тип возвращаемого значения должен быть UNIT, поэтому приведенный выше метод должен быть определен как

UINT Result::GetUnit() const {
    return unitobj;
}

Теперь посмотрите, как вы объявил этот метод в вашем классе

class Result
{
    ...
    Result GetUnit() const;

Здесь вы дали ему тип возвращаемого значения Result, где мы уже видели, что тип возвращаемого значения должен быть UINT, поэтому измените приведенное выше на

class Result
{
    ...
    UNIT GetUnit() const;

Result::GetDate имеет аналогичные проблемы, здесь тип возвращаемого значения должен быть Date, но вы снова указали его как Result.

Для ошибки SetResult вам просто нужно указать, что Вы вызываете метод SetResult для объекта Result. Компилятор считает, что вы вызываете глобальную SetResult функцию (которая не существует)

Как это

istream & operator >>( istream & input, Result & S)
{
      S.SetResult(input);
      return input;
}

S.SetResult(input); сообщает компилятору, что вы хотите вызвать SetResult метод с использованием объекта Result, на который ссылается S.

Вы можете сказать это, внимательно прочитав сообщение об ошибке, в котором говорится 'SetResult' was not declared in this scope, а не 'Result::SetResult' was not declared in this scope. Как вы сказали, вы объявили Result::SetResult, но ваш код не вызывал этого, он пытался вызвать другую функцию с именем SetResult, и компилятор правильно сообщил, что такая функция не была объявлена.

...