在构造函数中将指针传递给对象

时间:2014-06-02 08:35:13

标签: c++ oop

我想创建两个对象A和B,每个对象互相包含。

class B;

class A
{
public:
    A(B * b) : _b(b) {}
    void printB(void)
    {
        if (0 != _b)
        {
            std::cout << "B is not null" << std::endl;
        }
        else
        {
            std::cout << "B is null" << std::endl;
        }
    }
private:
    B * _b;
};

class B
{
public:
    B(A * a) : _a(a) {}
    void printA(void)
    {
        if (0 != _a)
        {
            std::cout << "A is not null" << std::endl;
        }
        else
        {
            std::cout << "A is null" << std::endl;
        }
    }
private:
    A * _a;
};

int main(int argc, char ** argv)
{
    A * a = 0;
    B * b = 0;

    a = new A(b);
    b = new B(a);

    a->printB();
    b->printA();

    delete a;
    delete b;

    return 0;
}

你可以看到对象&#39; a&#39;包含空指针&#39; b&#39;。重写此代码的最佳方法是什么,以便&#39; a&#39;包含对&#39; b&#39;的引用(请注意,对象&#39;以及&#39; b&#39;需要使用&#39; new&#39;)

非常感谢!

1 个答案:

答案 0 :(得分:4)

只需添加setB()方法,并在构建完两者后调用它。

#include <iostream>

class B;

class A
{
public:
    A(B * b) : _b(b) {}
    void setB(B* b) {
        this->_b = b;
    }
    void printB(void)
    {
        if (0 != _b)
        {
            std::cout << "B is not null" << std::endl;
        }
        else
        {
            std::cout << "B is null" << std::endl;
        }
    }
private:
    B * _b;
};

class B
{
public:
    B(A * a) : _a(a) {}
    void printA(void)
    {
        if (0 != _a)
        {
            std::cout << "A is not null" << std::endl;
        }
        else
        {
            std::cout << "A is null" << std::endl;
        }
    }
private:
    A * _a;
};

int main(int argc, char ** argv)
{
    A * a = 0;
    B * b = 0;

    a = new A(b);
    b = new B(a);
    a->setB(b);

    a->printB();
    b->printA();

    delete a;
    delete b;

    return 0;
}