【问题标题】:friend of a class doesn't access private values of a class in CPP类的朋友不访问 CPP 中类的私有值
【发布时间】: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 &amp;obj) 缺少它。
  • 签名差异friend Mystring operator-(const Mystring &amp;obj); vs Mystring operator-(Mystring &amp;obj)
  • 我内心深处的黑客喜欢你基于 strlen() 分配和释放内存,然后使用 strcpy() - 但这是一个更高级的课程:)
  • @bodn19888 Mystring operator-(Mystring &amp;obj) 不是成员函数或友元函数——它只是一个没有特殊访问权限的顶级函数。

标签: c++ oop friend


【解决方案1】:

简单错误:

一元减法operator- 的函数原型包含一个const,但在Mystrings.cpp 文件中被省略了。

【讨论】:

  • 问题不在于串联 (operator+),而在于一元减号 (operator-)。尽管发布的代码没有使用该运算符,但它的定义是报告错误的地方。这是唯一引用obj.str 的代码。如果你澄清这一点,你就会得到一个很好的答案。
  • @PeteBecker 完成!
猜你喜欢
  • 2021-08-16
  • 1970-01-01
  • 1970-01-01
  • 2015-11-24
  • 2015-03-06
  • 2014-06-18
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
相关资源
最近更新 更多