C++ setter函数崩溃
我有一个类被两个不同的类实例化,如下所示: 我在下面的代码中发生set_url()函数崩溃。无法确定原因?C++ setter函数崩溃
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类型的对象。
Vector<UrlAction> _url_act_list
在您声明a
时实例化,但最初_url_act_list
的大小为0。因此,当你尝试索引它时,你会得到一个段错误导致程序崩溃。
大概是正确的,但很难说,直到OP发布他们的Vector类。 – user4581301
a._url_act_list
为空。你可以
- 要么限定接纳尺寸的构造函数和您使用的大小只是
for
循环 之前访问它,即之前创建
- 或
resize
矢量相应 - 或者只是
push_back
元素到载体
vector
(在
A
和
B
)
第一个选项可能是这样的:
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
真的应该公开吗? (考虑选项3)有一个URLAction(string s)
构造函数会不会更容易?有些事情会让我感到不安,但这不是这个问题的一部分。
谢谢。添加了一个构造函数UrlAction(String from_url,bool act),它在创建对象时设置url和action,然后在vector中将其推入。 _url_act_list – Yogi
a._url_act_list
当您尝试为其调用operator[]
时为空。考虑
a._url_act_list.push_back({});
a._url_act_list.back().set_url(temp_vect[i]);
a.push_back(); ///推送什么? –
对不起,'a._url_act_list.push_back({})'。更新。 –
你能否请在邮寄中纠正它 –
您正在访问'_url_act_list'出界更换
。 –
另外,当使用字符串和向量的非标准版本时,至少要包含来自哪里的信息。 –
什么是'Vector'?什么是“字符串”? C++有'std :: vector'和'std :: string',那么这些以大写字母开头的版本是什么? – PaulMcKenzie