我有一个由两个不同类实例化的类,如下所示: 我在以下代码中遇到 set_url() 函数崩溃。无法决定为什么?
class UrlAction {
String url;
bool action;
public:
UrlAction() : action(false) {};
void operator=(const UrlAction &from);
inline String get_url() {
return url;
}
inline void set_url(String from_url) {
this->url = from_url;
}
inline bool get_action() {
return action;
}
inline void set_action(bool act) {
this->action = act;
}
};
class A {
public:
Vector<UrlAction> _url_act_list;
};
class B {
public:
Vector<UrlAction> _url_act_list;
};
foo() {
A a;
B b;
Vector<String> temp_vect;
temp_vect.push_back("xxxxx.com");
temp_vect.push_back("yyyyy.com");
temp_vect.push_back("zzzzz.com");
temp_vect.push_back("wwwww.com");
temp_vect.push_back("vvvvv.com");
for (int i = 0; i < temp_vect.size(); i++) {
a._url_act_list[i].set_url(temp_vect[i]); //This is the line causing crash
}
}
我还编写了一个“=”运算符重载器,用于分配两个 UrlAction 类型的对象。
最佳答案
a._url_act_list
为空。你可以
- 要么定义一个接收大小的构造函数,然后使用该大小创建
vector
(在A
和B
中) - 或
resize
vector 在访问它之前相应地调整大小,即在for
循环之前 - 或者只是将元素
push_back
到 vector 中
第一个选项可能如下所示:
A::A(size_t size) : { _url_act_list.resize(size) }
B::B(size_t size) : { _url_act_list.resize(size) }
第二个选项可能是这样的:
a.resize(temp_vect.size());
for (int i = 0; i < temp_vect.size(); i++) {
a._url_act_list[i].set_url(temp_vect[i]); //This is the line causing crash
}
第三个选项可能是这样的:
for (int i = 0; i < temp_vect.size(); i++) {
UrlAction url_action;
url_action->set_url(temp_vect[i]);
a._url_act_list.push_back(url_action); //This is the line causing crash
}
我相信您的代码可能设计得更好。 _url_act_list
真的应该公开吗?拥有一个 URLAction(string s)
构造函数不是更容易(考虑选项 3)吗?有些事情让我很烦恼,尽管这不是这个问题的一部分。
关于c++ - C++ setter 函数崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45518575/