0

Can't seem to get a simple stack implementation working. I'm simply trying to get two different classes (class B & class C) to be able to push and print element in the same stack being managed by a third class (class A).

A.cpp

#include "A.h"
void A::pop() {}
void A::push() {}
void A::print() {}  // prints last pushed elements

A.h

#include < iostream >
  class A 
  {
    public:
    void pop();
    void push();
    void print();
  }

B.cpp

#include "B.h"
#include "A.h"

A a;

void B::Text() { a.push(); }
void B::Background() { a.print(); }  // works!

C.cpp

#include "C.h"
#include "A.h"

A _a; // why doesn't A a work? because ODR?
void B::Text() { _a.push(); }
void B::Background() { _a.print(); } // doesn't work! breakpoint shows empty stack!

I think I'm breaking the One Definition Rule. Am I right?

4

2 回答 2

1

是的,每个变量必须只定义一次。extern A a在 C.cpp 中使用。

于 2015-05-28T09:16:25.513 回答
1

通过A a在 B.cpp 和A aC.cpp 中创建,您实际上有 2 个不同的对象,它们不会指向同一个堆栈。

实现相同目标的另一种方法是A作为单例对象。

于 2015-05-28T09:19:03.413 回答