从成员变量更新类变量或调用类功能是给出运行时错误
Updating class variable or calling class function from member variable is giving runtime error
我正在尝试实现更新,该更新将更新为所有Listerner类我正在使用类变量来计算侦听器的数量。 myClass 's正在扩展侦听器以从 updater class> class
聆听当我尝试从成员函数中使用类函数更新类变量时,我会遇到运行时错误。请参考以下代码,并帮助我分类此问题
#define MAX_LISTNERS 10
class Listner{
public:
virtual void onUpdate() = 0;
};
class Updater {
Listner* ptrListner[MAX_LISTNERS];
static int count;
public:
static void updateCount(){
count++;
}
void registerListner(Listner* ptrListner){
this->ptrListner[count] = ptrListner;
this->updateCount(); //---> Runtime Error
}
void updateToListner(){
for(int i=0;i<=count;i++){
this->ptrListner[i]->onUpdate();
}
}
};
int Updater::count = 0;
class MyClass: public Listner{
public:
void onUpdate(){
cout<<"update from MyClass";
}
};
class MyClass2: public Listner{
public:
void onUpdate(){
cout<<"update from MyClass2";
}};
int main() {
MyClass* obj = new MyClass();
MyClass2* obj2 = new MyClass2();
Updater obj_updater;
obj_updater.registerListner(dynamic_cast<Listner*>(obj));
obj_updater.registerListner(dynamic_cast<Listner*>(obj2));
obj_updater.updateToListner();
}
这里要考虑的几件事,因为这似乎有点不安全,而不是现代C 11方法。
- 使用RAII进行分配,即unique_ptr,而不是显式new/delete
- 使用std ::向量而不是C风格数组声明。您可以在运行时限制金额。这也为您提供了隐性的听众计数
- 让Updater类负责分配,工厂样式,这也使您可以尊重类型的安全
类似以下内容:
class Listner
{
public:
virtual void onUpdate() = 0;
};
class Updater
{
using ListnerPtr = std::unique_ptr<Listner>;
using Listners = std::vector<ListnerPtr>;
Listners m_listeners;
public:
template < typename T >
bool registerListner()
{
static_assert(std::is_base_of<Listner, T>::value, "T must be derived from Listner");
if (m_listeners.size() >= 10)
return false;
m_listeners.emplace_back(std::make_unique<T>());
return true;
}
void updateToListner()
{
std::for_each(m_listeners.begin(), m_listeners.end(), [](const Listners::value_type& item)
{
item->onUpdate();
});
}
};
class MyClass : public Listner
{
public:
void onUpdate() override
{
std::cout << "update from MyClass" << std::endl;
}
};
class MyClass2 : public Listner
{
public:
void onUpdate() override
{
std::cout << "update from MyClass2" << std::endl;
}
};
int main
{
Updater obj_updater;
obj_updater.registerListner<MyClass>();
obj_updater.registerListner<MyClass2>();
obj_updater.updateToListner();
return 0
}
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 对单向链表进行排序时出现运行时错误
- 为什么此代码存在运行时错误?
- 你能解释一下什么运行时错误是如何解决它的吗?
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- 运行时错误:引用绑定到类型为"int"的空指针
- 为什么当 vector 为空时会显示运行时错误?
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 运行时错误:矢量下标超出范围:正在检查空集
- 分配给gslice_array会导致运行时错误
- cout 新创建的对象引发运行时错误
- C++在使用std::multimap时出现运行时错误的几率很小
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 试图找出为什么我会收到运行时错误?
- 从成员变量更新类变量或调用类功能是给出运行时错误
- 自定义char*插入功能多次运行时会产生运行时错误