[英]Using a pointer to an object as a member of another object
For certain reasons, I want to have multiple instances of class A all have access to a single instance of class B. B has public member functions that allow objects of A to get data from B, but not to change it.出于某些原因,我希望 class A 的多个实例都可以访问 class B 的单个实例。B 具有公共成员函数,允许 A 的对象从 B 获取数据,但不能更改它。 I'm trying to do this by declaring an object of B in my main function, then passing it to the constructor when I declare objects of type A.
我试图通过在我的主 function 中声明 B 的 object 来做到这一点,然后在我声明类型 A 的对象时将其传递给构造函数。
void main () {
B obj_b;
A A1(obj_b);
A A2(obj_b);
A A3(obj_b);
cout << A1.getfoo() << endl;
cout << A2.getfoo() << endl;
count << A3.getfoo() << endl;
}
class B{
private:
int foo = 9;
public:
int getfoo(){return foo;}
};
class A {
private:
B *bptr;
public:
A(B b){ this->bptr = &b; }
int getfoo(){ return bptr->getfoo(); }
};
This compiles and runs, but I get very weird results.这编译并运行,但我得到非常奇怪的结果。 The return values from getfoo are sometimes correct sometimes incorrect.
getfoo 的返回值有时正确有时不正确。 Am I handling the pointers incorrectly?
我是否错误地处理了指针? Is there a better way to do this?
有一个更好的方法吗?
In the A
constructor, the argument b
is a local variable, its life-time ends when the constructor function ends.在
A
构造函数中,参数b
是一个局部变量,它的生命周期在构造函数 function 结束时结束。 You can't save a pointer to it, that pointer will become invalid immediately.您不能保存指向它的指针,该指针将立即失效。
Either use smart pointers , or use a reference and constructor initializer lists :要么使用智能指针,要么使用引用和构造函数初始化列表:
class A
{
public:
// Pass by reference
A(B& b)
: b{ b } // Initialize the member variable b with the argument b
{
// Empty body
}
private:
B& b; // Reference to a B object
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.