【发布时间】:2020-08-13 17:45:02
【问题描述】:
我想问一个关于 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,但错误仍然存在。连接运算符+ 正常工作,但我无法弄清楚上述错误为何仍然存在。
为什么会产生这个错误?
【问题讨论】:
-
朋友有一个
const,你注意到了吗?Mystring operator-(Mystring &obj)缺少它。 -
签名差异
friend Mystring operator-(const Mystring &obj);vsMystring operator-(Mystring &obj) -
我内心深处的黑客喜欢你基于 strlen() 分配和释放内存,然后使用 strcpy() - 但这是一个更高级的课程:)
-
@bodn19888
Mystring operator-(Mystring &obj)不是成员函数或友元函数——它只是一个没有特殊访问权限的顶级函数。