关于C++的问题,求大神详解

2025-06-20 20:11:48
推荐回答(3个)
回答1:

  • #include 
    #include 
    using namespace std;
    class C
    {
    char c1; char c2;
    public:friend void set(C &s, char c1, char c2);
      C(char a, char b)
      {
      c1 = a; c2 = b;
      cout << "C constructor" << endl;
      }
      C(const C &rhs)
      {
      c1 = rhs.c1;
      c2 = rhs.c2;
      cout << "C copy" << endl;
      }
      C &operator = (C const &rhs)
      {
      c1 = rhs.c1;
      c2 = rhs.c2;
      cout << "C operator" << endl;
      return *this;
      }
      ~C()
      {
      cout << "c1=" << c1 << ";c2="<  }
    };
    void set(C &s, char c, char d){ s.c1 = c; s.c2 = d; }
    C fun(C obj){ set(obj, '7', '9'); return obj; }
    void main()
    {
    C obj('7', '8');
    C obj1 = obj;
    obj1 = fun(obj);

回答2:

因为你的fun是值传递,又拷贝了一个。

回答3: