问题描述
我想问一个关于C ++类的朋友的问题。
我是C ++的初学者,并且学习重载运算符作为全局函数。
我在Mystrings.h
文件中编写了类声明的以下部分,并在Mystrings.cpp
文件中编写了相应的函数。
Mystrings.h
:
class Mystring
{
friend bool operator==(const Mystring &lhs,const Mystring &rhs);
friend Mystring operator-(const Mystring &obj);
friend Mystring operator+(const Mystring &lhs,const Mystring &rhs);
private:
char *str; // pointer to a char[] that holds a c-style string
和Mystrings.cpp
:
Mystring operator-(Mystring &obj) {
char *buff = new char[std::strlen(obj.str)+1];
std::strcpy(buff,obj.str);
for (size_t i = 0; i < std::strlen(buff); i++)
buff[i] = std::tolower(buff[i]);
Mystring temp {buff};
delete [] buff;
return temp;
}
// concatenation
Mystring operator+(const Mystring &lhs,const Mystring &rhs) {
char *buff = new char [std::strlen(lhs.str) + std::strlen(rhs.str) + 1];
std::strcpy(buff,lhs.str);
std::strcat(buff,rhs.str);
Mystring temp {buff};
delete [] buff;
return temp;
}
对于我的主要CPP文件,我试图进行以下工作:
Mystring three_stooges = moe + " " + larry + " " + "Curly";
three_stooges.display(); // Moe Larry Curly
但是,编译器返回错误:
error: 'str' is a private member of 'Mystring'
一行
char *buff = new char[std::strlen(obj.str)+1];
std::strcpy(buff,obj.str);
我似乎不明白为什么。
我知道在声明该函数的朋友时,他们现在可以访问私有字符串指针*str
,但错误仍然存在。串联运算符+
的功能正常,但是我无法弄清楚为什么上述错误仍然存在。
为什么会产生此错误?
解决方法
简单错误:
一元减operator-
的函数原型包含一个const
,但在Mystrings.cpp
文件中被省略。