【问题标题】:how to write a function such that if we print a object then it's need to print a arguments passed in object如何编写一个函数,如果我们打印一个对象,那么它需要打印一个传入对象的参数
【发布时间】:2020-10-01 19:42:39
【问题描述】:

在类库中,我们需要编写一个函数,以便打印对象将使用 oops 概念打印对象的参数。

#include <iostream>
using namespace std;
class base{
    int num;
    string s;
    public:
    base(int elem,string p){
        cout<<elem<<" "<<p<<endl;
    }
    // todo:

};
int main() {
    base obj(12,"shivam");
   // cout<<obj<<endl;
}

【问题讨论】:

  • 查看this 问题,它解决了打印问题。对于传递给obj 的参数,请查看构造函数。
  • 如果你搜索“c++重载输出”,你会发现很多教程。

标签: c++ oop


【解决方案1】:

您当前的想法离工作不远了,除非您在创建base 的实例后立即将构造函数参数打印到std::cout - 而不是在使用该类的程序员表达这样的愿望时。您需要做的是保存构造base 时给出的参数。然后您就可以按需打印它们了。

例子:

#include <iostream>
#include <string>

class base {
public:
    base(int n, const std::string& str) : //    save the arguments given using
        num(n), s(str)                    // <- the member initializer list
    {
        // empty constructor body
    }
    // declare a friend function with special privileges to read private
    // member variables and call private functions:
    friend std::ostream& operator<<(std::ostream&, const base&);

private:
    int num;
    std::string s;
};

// define the free (friend) function with access to private base members:
std::ostream& operator<<(std::ostream& os, const base& b) {
    // here you format the output as you'd like:
    return os << '{' << b.num << ',' << b.s << '}';
}

int main() {
    base obj(12,"shivam");
    std::cout << obj << '\n';
}

输出:

{12,shivam}

【讨论】:

  • 你能解释一下为什么你使用return by reference吗?
  • @ShivamJain 引用与 C++ 中的一样轻量级。引用甚至不需要占用实际内存。在上面的ostream 案例中,由于另一个原因,它很重要。示例 the_ostream &lt;&lt; a &lt;&lt; b 这是链接两个操作,如下所示:(the_ostream &lt;&lt; a) &lt;&lt; b 只有当 the_ostream &lt;&lt; a 返回对 b 应该流入的相同 ostream 的引用时才有可能。也许不是最好的解释,但如果我没有说得更清楚,请再问一次。
【解决方案2】:

试试这个:

  int IntS(int y)
  {
       return y;
  }

  class base{
  public:
        base(int enume, std::string str)
        {
             std::cout << IntS(enume) << '\n';
             std::cout << str << '\n;
        }

    };

    int main()
    {
         base mybase(IntS(5), "five");
         return 0;
    }

另见,std::map:

How can I print out C++ map values?

【讨论】:

    猜你喜欢
    • 2012-01-11
    • 2017-09-30
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2016-02-16
    • 1970-01-01
    相关资源
    最近更新 更多