我如何拥有一个 getter 那个 returns 另一个对象的指针?

How do I have a getter that returns a pointer of another object?

我在网上找到了以下获取另一个对象的对象 class:

Class A{
.........
 B b;
.........
const B& getB()const{
return b;
}

};

和以下获取指向另一个对象的指针 class:

Class A{
.........
B* b;
void setB(B *x) { b=x; }
B *getB() const { return b; }
.........


};

我有以下情况:

 Class A{
.........
 B** b;
 A(int i){ b = new B*[i] ;}
.........
};

我想 return 来自 A.So 的 B* new a(4)->getB() 将 return b[4]。我是否执行以下操作:

    Class A{
    .........
     B** b;
     A(int i){ b = new B*[i] ;}
    .........
    const B&* getB() const{ return b; }
   ........
    };

我的意图是 return 我在另一个 class.

的构造函数中初始化的对象指针数组中的一个对象
const B** getB() const{ return b; }

这就是你想要的?

与其使用原始指针,不如考虑使用一些容器(std::vector?)或智能指针。如果不是,请提供一些关于您的问题的更好的信息。

编辑

I want to return an object from an array of object pointers of another class

好的

const B* getB(size_t index) const{ return b[index]; }

这将return指向先前存储为数组第五个元素的指向常量 B 的指针的引用。

const B*& getB() const{ return b[4]; }

注意你的用法。 new a(4)->getB() 将调用未定义的行为,因为数组中只有四个元素。