прекращение вызова после выброса экземпляра ‘std :: logic_error’ what (): basic_string :: _ M_construct null недопустимо

Вот инструкции:

В главе 10 класс clockType был разработан для реализации времени суток в программе. Для некоторых приложений, помимо часов, минут и секунд, может потребоваться сохранение часового пояса.
Выведите класс extClockType из класса clockType
добавив переменную-член для хранения часового пояса. Добавьте необходимые функции-члены и конструкторы, чтобы сделать класс функциональным. Кроме того, напишите определения функций-членов и конструкторов. Наконец, напишите тестовую программу для проверки вашего класса.

Вот мои файлы:

clockType.h

//clockType.h, the specification file for the class clockType

#ifndef H_ClockType

#define H_ClockType

class clockType

{

public:

void setTime(int hours, int minutes, int seconds);

//Function to set the time.

//The time is set according to the parameters.

//Postcondition: hr = hours; min = minutes;

// sec = seconds

// The function checks whether the values of

// hours, minutes, and seconds are valid. If a

// value is invalid, the default value 0 is

// assigned.

​

void getTime(int& hours, int& minutes, int& seconds) const;

//Function to return the time.

//Postcondition: hours = hr; minutes = min;

// seconds = sec

​

void printTime() const;

//Function to print the time.

//Postcondition: The time is printed in the form

// hh:mm:ss.

​

void incrementSeconds();

//Function to increment the time by one second.

//Postcondition: The time is incremented by one

// second.

// If the before-increment time is 23:59:59, the

// time is reset to 00:00:00.

​

void incrementMinutes();

//Function to increment the time by one minute.

//Postcondition: The time is incremented by one

// minute.

// If the before-increment time is 23:59:53,

// the time is reset to 00:00:53.

​

void incrementHours();

//Function to increment the time by one hour.

//Postcondition: The time is incremented by one

// hour.

// If the before-increment time is 23:45:53, the

// time is reset to 00:45:53.

​

bool equalTime(const clockType& otherClock) const;

//Function to compare the two times.

//Postcondition: Returns true if this time is

// equal to otherClock; otherwise,

// returns false.

​

clockType(int hours, int minutes, int seconds);

//constructor with parameters

//The time is set according to the parameters.

//Postcondition: hr = hours; min = minutes;

// sec = seconds

// The constructor checks whether the values of

// hours, minutes, and seconds are valid. If a

// value is invalid, the default value 0 is

// assigned.

​

clockType();

//default constructor with parameters

//The time is set to 00:00:00.

//Postcondition: hr = 0; min = 0; sec = 0

private:

int hr; //variable to store the hours

int min; //variable to store the minutes

int sec; //variable to store the seconds

};

#endif

clockTypeImp.cpp

//Implementation File for the class clockType

#include <iostream>

#include "clockType.h"
​

using namespace std;

void clockType::setTime(int hours, int minutes, int seconds)

{

if (0 <= hours && hours < 24)

hr = hours;

else

hr = 0;

​

if (0 <= minutes && minutes < 60)

min = minutes;

else

min = 0;

​

if (0 <= seconds && seconds < 60)

sec = seconds;

else

sec = 0;

}

​

void clockType::getTime(int& hours, int& minutes,

int& seconds) const

{

hours = hr;

minutes = min;

seconds = sec;

}

​

void clockType::incrementHours()

{

hr++;

if (hr > 23)

hr = 0;

}

​

void clockType::incrementMinutes()

{

min++;

if (min > 59)

{

min = 0;

incrementHours();

}

}

​

void clockType::incrementSeconds()

{

sec++;

​

if (sec > 59)

{

sec = 0;

incrementMinutes();

}

}

​

void clockType::printTime() const

{

if (hr < 10)

cout << "0";

cout << hr << ":";

​

if (min < 10)

cout << "0";

cout << min << ":";

​

if (sec < 10)

cout << "0";

cout << sec;

}

​

bool clockType::equalTime(const clockType& otherClock) const

{

return (hr == otherClock.hr

&& min == otherClock.min

&& sec == otherClock.sec);

}

​

clockType::clockType(int hours, int minutes, int seconds)

{

if (0 <= hours && hours < 24)

hr = hours;

else

hr = 0;

​

if (0 <= minutes && minutes < 60)

min = minutes;

else

min = 0;

​

if (0 <= seconds && seconds < 60)

sec = seconds;

else

sec = 0;

}

​

clockType::clockType() //default constructor

{

hr = 0;

min = 0;

sec = 0;

}

​

(даны первые 2 файла)

(начиная здесь я создаю код)

extClockType.h

​

#ifndef H_extClockType

#define H_extClockType

#include<iostream>

#include "clockType.h"
using namespace std;

​

class extClockType: public clockType

{

public:

extClockType();

extClockType(int, int, int, string);

void setTime(int hours, int minutes, int seconds, string zone);

string printTimezone();

string getTimezone();

private:

string zone;

};

#endif

extClockTypeImp.cpp

#include <iostream>

#include "clockType.h"
#include "extClockType.h"
​

using namespace std;

extClockType::extClockType(): clockType()

{

zone = "na";

}

​

extClockType::extClockType(int hours, int minutes, int seconds, string time_zone)

{

clockType::setTime(hours, minutes, seconds);

zone = time_zone;

}

void extClockType::setTime(int hours, int minutes, int seconds, string zone)

{

clockType::setTime(hours, minutes, seconds);

}

string extClockType::getTimezone()

{

return zone;

}

​

string extClockType::printTimezone()

{

clockType::printTime();

cout << " " << zone << endl;

return 0;

}

main.cpp

#include <string>

#include <iomanip>

#include <iostream>

#include "clockType.h"
#include "extClockType.h"
​

using namespace std;

​

int main()

{

extClockType time1(5, 10, 34, "CST");

cout << "Time 1: ";

time1.printTimezone();

cout<<endl;

extClockType time2;

time2.setTime(12, 45, 59, "PST");

cout<< "Time 2: ";

time2.printTimezone();

cout<<endl;

​

time2.incrementSeconds();

cout<< "After incrementing time 2 by one second, Time 2:";

time2.printTime();

}

​

Это мое сообщение об ошибке:

Time 1: 05:10:34 CST

terminate called after throwing an instance of 'std::logic_error'

what(): basic_string::_M_construct null not valid

Извините за длинное сообщение, я просто хотел показать все файлы, с которыми я работаю. Если кто-нибудь захочет помочь мне, это будет огромной помощью!

2

Решение

Ошибка просто означает, что вы вызвали строковый конструктор:

std::string::string(const char *p);

с NULL указатель, который недопустим.

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

3

Другие решения

Одна ошибка заключается в следующем:

string extClockType::printTimezone()
{
clockType::printTime();
cout << " " << zone << endl;
return 0;  // This is not legal, converting an int to a std::string
}

По возвращении вы возвращаетесь 0 и это пытаются преобразовать в std::string, Нет конструктора для std::string это занимает int аргумент (в этом случае 0). Вместо этого будет выдано исключение.

Вы должны вернуть либо ничего (таким образом, функция должна быть объявлена ​​как возвращающая void) или вернуть что-то, что создает действительный std::string,

Примечание: конструктор, который был вызван для std::string это тот, который занимает один const char * аргумент (см. конструктор (5)). В этом случае, 0 преобразуется в nullptrТаким образом, по возвращении std::string(nullptr) пытается быть построен.

1

Легко ведь

string extClockType::printTimezone() {
...
return 0;
}

Измените это на это и обновите прототип:

void extClockType::printTimezone() {
...
return;
}

Это пытается создать std :: string с 0, интерпретируемым как nullptr. Возвращаемое значение должно быть недействительным в зависимости от использования.

После исправления вывод будет:

Время 1: 05:10:34 CST

Время 2: 12:45:59 на

После увеличения времени 2 на одну секунду, Время 2: 12: 46: 00

Обратите внимание, что «на» является результатом

void setTime(int hours, int minutes, int seconds, string zone);

фактически не устанавливает переменную-член ‘zone’.

0
По вопросам рекламы [email protected]