【问题标题】:overloaded extraction operator won't friend in C++重载的提取运算符不会在 C++ 中成为朋友
【发布时间】:2021-09-19 21:27:13
【问题描述】:

我正在处理提取和插入重载。而且我在使用朋友时无法访问私有变量。

这是我基于标准教程的代码以及我的老师让我使用的代码

Main.cpp

#include <iostream>
#include "Obj.h"

using namespace std;
using namespace N;

Obj a;

int main() {
  cout << a;
}

Obj.cpp

#include "Obj.h"
#include <iostream>

using namespace std;
using namespace N;

ostream &operator<<(ostream &output, const Obj &a) {
    output << a.h;
    return output;
}

对象.h

#ifndef OBJ_H
#define OBJ_H

#include <iostream>

using namespace std;

namespace N {
    class Obj {
        private:
        string h; 

        public:

        //constructors
        Obj() {
            h = "default";
        }

        //overloads
        friend ostream &operator<<(ostream &output, const Obj &a);
    };
}

#endif

我从头文件设置开始,并在得到相同的错误代码时将其分解为这个。特别是我一直得到这个结果。

Obj.cpp:9:15: error: 'h' is a private member of 'N::Obj'
  output << a.h;
              ^
./Obj.h:12:14: note: declared private here
      string h; 

【问题讨论】:

  • 不能reproduce
  • 欢迎来到 Stack Overflow!您能否编辑您的问题以显示您正在使用的 .h.cpp 文件的确切内容?您上面显示的代码应该可以正常工作,这让我认为可能发生了其他事情。
  • 我的水晶球(例如它)表明您的重载(朋友)&lt;&lt; 运算符的声明和定义之间存在非常小的差异。可能是缺少const&amp;
  • 我可以做的更好,向你展示这个项目。 replit.com/@QuietQuiet/Insertion-Operator#main.cpp我也会编辑问题

标签: c++ operator-overloading extract friend


【解决方案1】:

问题在于您在namespace N 中声明了friend 函数,但您在全局命名空间中定义了它。 using namespace N; 没有在命名空间中放置任何定义,它只会让编译器猜测它应该来自该命名空间如果它有其他线索(例如,你正在定义一个类的方法)。在这里,没有什么建议这个运算符不应该在全局命名空间中,所以它就在那里。

解决方案是正确使用命名空间:

#include "Obj.h"
#include <iostream>

using namespace std;
namespace N {

ostream & operator << (ostream &output, const Obj &a){
  output << a.h;
  return output;
}

}

当我们这样做的时候,using namespace std; is not a good practice 也是。

【讨论】:

  • N::operator&lt;&lt;
【解决方案2】:

&lt;&lt; 的主体放入类声明中。

可以短至a.printTo(output); return output;

然后写printTo

将名称作为朋友声明引入的规则有时很棘手。我猜你的真实代码,Obj 是一个模板,或者一些小的 chsnge 搞砸了匹配等等。上述模式回避了这些问题。

【讨论】:

  • 学习朋友并使用这是作业,但我可以尝试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多