如何在构造函数之后设置引用?

How I set a reference after constructor?

本文关键字:设置 引用 之后 构造函数      更新时间:2023-10-16

我想在构造函数之后设置一个引用

例:

class OtherClass
{
public:
OtherClass() : m_class(Class()){}
inline void SetData(int data1, int data2)
{
//calculate data3
// I tried:
m_class = Class(data3);
//but it doesn't worked
}
protected:
private:
Class& m_class;
};

编辑:

  • 例外情况是:矢量下标超出范围 因为我在类中有 glm 向量。
  • 我还需要在我的类中调用函数。

编辑 2:

为什么我需要这个?因为我有另一个类 [ExClass] 它扩展并且必须在构造函数中计算:

ExClass::ExClass(float d1, float d2, ...) {
//calculate data from given values
SetData(data); 
}

正确的方法是使用指针而不是引用,而不是引用 - 指针可以在对象创建后设置。另请注意,引用(或指向(其生存期将结束的局部变量(仍在使用中(是一个坏主意。

您的代码可以更改为使用指针和动态分配,或者std::unique_ptr.当然还有其他选择,这些只是例子。

选项 1 - 指针和动态分配

class OtherClass
{
public:
OtherClass() : m_class(nullptr){}
~OtherClass() {
delete m_class;
}
// block copy and assignment (or implement them)
OtherClass(const OtherClass&) = delete;
OtherClass& operator=(const OtherClass&) = delete;
void setData(int data1, int data2)
{
// ... calculate data3 ...
m_class = new Class(data3);
}
bool hasInnerObj() const {
return m_class; // or: return m_class != nullptr;
}
/** call this function only if hasInnerObj() returned true */
Class& getInnerObj() {
return *m_class;
}
private:
Class* m_class;
};

选项 2 - 标准::unique_ptr

class OtherClass
{
public:
void setData(int data1, int data2)
{
// ... calculate data3 ...
m_class = std::make_unique<Class>(data3);
}
bool hasInnerObj() const {
return m_class; // or: return m_class != nullptr;
}
/** call this function only if hasInnerObj() returned true */
Class& getInnerObj() {
return *m_class;
}
private:
std::unique_ptr<Class> m_class;
};

您有两个问题:

  1. 引用类成员(即m_class( 需要在创建对象时初始化。
  2. 但是,您的两个Class实例(一个在构造函数中,一个在SetData中(都放在堆栈上并立即弹出,使引用无效。

你需要做的是确保你的类对象实际上通过函数调用存在。实现此目的的一种方法是在将其传递给OtherClass构造函数或SetData函数之前分配它:

class Class {};
class OtherClass
{
public:
OtherClass(Class& c) : m_class(c){}
inline void SetData(Class& c)
{
m_class = c;
}
protected:
private:
Class& m_class;
};
int main()
{
Class a;
OtherClass c(a);
Class b;
c.SetData(b); // changes m_class
return 0;
}

活生生的例子在这里。