在构造函数中传递指向对象的指针

che*_*chi 1 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;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,对象“a”包含空指针“b”。重写此代码以便“a”包含对“b”的引用的最佳方法是什么?(注意对象'a'和'b'需要使用'new')

非常感谢!

mer*_*011 5

只需添加一个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;
}
Run Code Online (Sandbox Code Playgroud)