我正在处理一个项目,我们不允许使用<string>
库 - 我们只能使用字符串作为字符指针,并且必须为它们编写自己的函数(如strcpy、strlen等)。我正在尝试构建一个RentalCar类,其头文件如下:
#ifndef RENTALCAR_H
#define RENTALCAR_H
class RentalCar {
public:
RentalCar();
RentalCar(char* make, char* model);
char* getMake() const;
char* getModel() const;
void setMake(char* make = "");
void setModel(char* model = "");
private:
char m_make[256];
char m_model[256];
};
#endif
我的源文件包含以下内容:
#include <iostream>
#include "RentalCar.h"
using namespace std;
RentalCar::RentalCar() {
setYear();
setMake();
setModel();
setPrice();
setAvailable();
}
RentalCar::RentalCar(int year, char* make, char* model, float price,
bool available) {
setYear(year);
setMake(make);
setModel(model);
setPrice(price);
setAvailable(available);
}
char* RentalCar::getMake() const{
return m_make;
}
char* RentalCar::getModel() const{
return m_model;
}
void RentalCar::setMake(char* make) {
myStringCopy(m_make, make);
}
void RentalCar::setModel(char* model) {
myStringCopy(m_model, model);
}
char* myStringCopy(char* destination, const char* source) {
int index = 0;
while(*(source + index) != '\0') {
*(destination + index) = *(source + index);
index++;
}
*(destination + index) = '\0';
return destination;
}
我的问题是,在我的getMake和getModel方法中,我遇到了以下错误:
cannot initialize return object of type 'char *'
with an lvalue of type 'char const[256]'
我不确定如何构造默认字符串,而不是文字 - 这就是为什么我认为我会得到这个错误的原因。
我还有一个问题是,在设置setMake()和setModel()函数中的字符串时,我需要使用myStringCopy()函数,那么我应该将其作为类中的一个函数包含进去,还是有其他方法可以访问它?我也需要在我的实际项目文件中使用它,但在那里和RentalCar.cpp中都包含它感觉很冗余。
值得一提的是,我们不允许以任何方式使用数组索引来处理字符串 - 除了初始化新字符串。
任何帮助都将不胜感激!谢谢!
std::string
一样复杂,但封装字符串管理和比较会使使用它的代码更加容易编写。 - NathanOliverstd::string
从那时起就可用。这已经是一代人的时间了。你能想象一个电视维修课程教如何更换真空管吗? - PaulMcKenzie