【问题标题】:operator << overloading for class [duplicate]运算符<<类重载[重复]
【发布时间】:2018-06-01 08:22:06
【问题描述】:

A是我写的一个C++类:

class A
{
private:
    int _num1;
    int _num2;
public:
    A(int num1, int num2)
    {
        _num1 = num1;
        _num2 = num2;
    }

    ~A(){}

    int getNum1() { return _num1; };
    std::ostream &operator<<(std::ostream &os, A const &obj) { return os << obj.getNum1(); };
};

有一个模板的函数printArray:

template <class T>
void printArray(T* arr, int size)
{
    int i = 0;
    for (i = 0; i < size; i++)
        cout << arr[i] << endl;
}

当我写在主函数中时:

    A arr4[4] = { A(1,1), A(1,4), A(6,6), A(0,0) };
    printArray(arr4, 4);

有这个错误:

E0344 此运算符函数的参数过多。

C2804 二进制 'operator

C2333 'A::operator

问题是什么以及如何解决?

当然我包括 iostream

【问题讨论】:

  • friend放在std::ostream之前
  • 没有帮助,给出:> C2662 'int A::getNum1(void)': 无法将 'this' 指针从 'const A' 转换为 'A &'

标签: c++ class templates operator-overloading


【解决方案1】:

你有两个问题: 1.你应该使用friend关键字来重载&lt;&lt;操作符 2.getNum1应该是const

class A
{
private:
    int _num1;
    int _num2;
public:
    A(int num1, int num2)
    {
        _num1 = num1;
        _num2 = num2;
    }

    ~A() {}

    int getNum1() const { return _num1; };
    friend std::ostream &operator<<(std::ostream &os, A const &obj) { return os << obj.getNum1(); };
};

【讨论】:

  • 它现在可以工作,但是 printArray 现在打印出了问题:1 49305896 6 2
  • @arik 您的代码,在按照上述进行更正后,可以毫无问题地为我工作。我有 1 1 6 0
  • 你写,我的其他功能也出错了,解决了
猜你喜欢
  • 2021-09-19
  • 2014-02-25
  • 2015-06-20
  • 1970-01-01
  • 2011-10-27
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 2012-12-22
相关资源
最近更新 更多