문제

I have the following classes implemented:

class NUMS {
   int* numbers;
   int size;
  public:
   ostream& operator << (ostream& out, NUMS const& nums) {
       for (int i = 0; i < size; ++i) out << nums.numbers[i] << " \n";
       return out;
   } 
};

class A

class B : public A {
   NUMS* numbers;
   public:
     C& func() {
         C* c = new C();
         return *c;
     }
     ostream& operator << (ostream& out, B const& b) {
        for (int i = 0; i < b.numbers->get_size(); ++i) out << b.numbers[i];
        return out;
     }
};

class C : public B

In my main:

A* a = new B();
B& b = a->func();
cout << a;
cout << b;

The ostream operator doesn't work at cout << b. what is my problem?

도움이 되었습니까?

해결책

Firstly, your operator << overload should be a global operator, and it should also be a friend of the class so it can have access to the class' private data members:

friend ostream& operator << (ostream& out, NUMS const& nums)
{
    // ...
}

The same also goes for the << overload in B.

You're mostly likely getting undefined behavior in func, but what I think you should do is remove all instances of pointers and new in your code, as they aren't needed. new is not used to create instances of classes, it actually allocates dynamic memory.

Your func method could return a stack-allocated instance of A instead:

C func()
{
   return C();
}

It should also return it by-value because returning by reference would cause a dangling reference immediately after the ending brace because the temporary object will have already been destroyed.

I think you're confused about what the following lines are doing:

cout << a;
cout << b;

The first one prints out the value of the pointer (i.e an address). It isn't calling any operator overload in this case. The compiler won't even get to print b because of the incorrect lines before it.

If you want cout << b to work, you must change the way you initialize it. From this:

B& b = a->func();

to simply

B b;

Printing out b from there should work. I'm not sure about what you're trying to do with a->func() or the C class, I don't think there's even any reason for it in your program.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top