如何在构造函数之后设置引用?
How I set a reference after constructor?
我想在构造函数之后设置一个引用
例:
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;
};
您有两个问题:
- 引用类成员(即
m_class
( 需要在创建对象时初始化。 - 但是,您的两个
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;
}
活生生的例子在这里。
相关文章:
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- C++(和 ROS) - 包含与前向声明引用,设置默认值和类型定义
- 如何在引用上设置数据断点
- 使用 sscanf 设置结构引用的值
- 将函数的引用设置为其他 c++ 文件中的非静态函数
- 通过初始化列表设置抽象类的引用
- 将常量引用成员设置为临时变量是否安全
- 对象超出范围后,引用成员设置为 0
- 为什么设置/get_default_resource使用指针而不是引用?
- 在构造函数中设置引用?
- 如何在构造函数之后设置引用?
- 通过引用设置类时会发生什么情况
- 从函数返回 libconfig 类设置对象引用
- qt vsaddin错误对象引用未设置为对象的istanse
- 设置可变值通过字符串引用它
- 在 ONE 设置中添加附加包含目录并引用 => 指向静态库
- 为什么我们需要在move构造函数中将右值引用设置为null
- 如果指针设置为 NULL,则对它的任何引用都不会或通过它也是 NULL
- 未在另一个函数中设置变量引用的问题
- C++类中设置引用变量,然后进行更改