[英]Overloading Operators with char c++
I am working on a homework for class on overloading operators. 我正在为超载运算符上课的家庭作业。 The problem I am having is with a char.
我遇到的问题是字符。
RetailItem &RetailItem::operator=(const RetailItem &objRetail) {
this->description = objRetail.getDescription();
this->unitsOnHand = objRetail.getUnitsOnHand();
this->price = objRetail.getPrice();
return *this;
}
I am getting a message on Visual Studio: 我在Visual Studio上收到一条消息:
a value of type
const char *
cannot be assigned to an entity of typechar *
.不能将类型
const char *
的值分配给char *
类型的实体。
I have done some research and not found anything. 我已经做了一些研究,但没有发现任何东西。 If anyone can help, thanks in advance.
如果有人可以帮助,请提前感谢。
EDIT: 编辑:
I will add the getDescription
function to provide more information. 我将添加
getDescription
函数以提供更多信息。 Also the description is a *char
. 此外,描述内容为
*char
。
const char *RetailItem::getDescription() const{
return description;
}
Probably RetailItem::description
is char*
and RetailItem::getDescription
casts this char*
to const char*
and returns that. 可能
RetailItem::description
是char*
而RetailItem::getDescription
将此char*
强制转换为const char*
并返回。 You can add const
qualifiers implicitly, but you cannot remove them the same way in the assignment: 您可以隐式添加
const
限定词,但是不能以相同的方式在分配中删除它们:
this->description = objRetail.getDescription();
And you probably shouldn't . 而且你可能不应该 。 This will make two
RetailItem
s referring to the same resource without managing its lifetime properly, as well as not freeing the memory held previously (if it is indeed a pointer to a dynamically allocated array). 这将使两个
RetailItem
引用同一个资源,而没有适当地管理其寿命,也不会释放先前持有的内存(如果它确实是指向动态分配数组的指针)。
This boils down to: you should prefer using std::string
over arrays. 归结为:您应该更喜欢使用
std::string
不是数组。
Reason might be mismatch between data type of "member variables" which you used in the class and the return values of the function. 原因可能是您在类中使用的“成员变量”的数据类型与函数的返回值不匹配。
const char *RetailItem::getDescription() const{
return description;
}
Remove const before function , keep it char *RetailItem::getDescription() const only .It should work 删除函数前的const,保留它为char * RetailItem :: getDescription()const。它应该可以工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.