我正在尝试将字符串传递给类mutator,并将私有成员设置为该字符串,这里是发送字符串的代码
void parseTradePairs(Exchange::Currency *curr, std::string *response, int begin, int exit)
{
int start;
int end;
string temp;
string dataResponse;
CURL *tempCurl;
initializeCurl(tempCurl);
int location = response->find("marketid", begin);
if(location <= exit)
{
start = location + 11;
begin = response->find("label", start);
end = begin - start - 3;
findStrings(start, end, temp, response);
getMarketInfo(tempCurl, temp, dataResponse);
curr->_coin->setExch(temp); // here is the line of code that is sending the string
dataResponse >> *(curr->_coin);
curr->_next = new Exchange::Currency(curr, curr->_position + 1);
parseTradePairs(curr->_next, response, begin, exit);
}
}
这里是硬币类中的mutator,它接收字符串并将其分配给_exch
void Coin::setExch(string exch)
{
_exch = exch;
}
我已经介入它并确保exch中包含字符串。 “105”,但很快就会发出_exch = exch;我得到了阅读违规。我也试过传递指针。我不相信它应该超出范围。并且类中的字符串变量在默认构造函数中初始化为零,但除非我尝试从中读取而不是写入它,否则这应该重要。
/* defualt constructor */
Coin::Coin()
{
_id = "";
_label = "";
_code= "";
_name = "";
_marketCoin = "";
_volume = 0;
_last = 0;
_exch = "";
}
Exchange::Exchange(std::string str)
{
_exch = str;
_currencies = new Currency;
std::string pair;
std::string response;
CURL *curl;
initializeCurl(curl);
getTradePairs(curl, response);
int exit = response.find_last_of("marketid");
parseTradePairs(_currencies, &response, 0, exit);
}
int main(void)
{
CURL *curl;
string str;
string id;
Coin coin1;
initializeCurl(curl);
Exchange ex("cryptsy");
curl_easy_cleanup(curl);
system("pause");
return 0;
}
class Exchange
{
public:
typedef struct Currency
{
Currency(Coin *coin, Currency *next, Currency *prev, int position) : _coin(coin), _next(next), _prev(prev), _position(position) {}
Currency(Currency *prev, int position) : _prev(prev), _position(position), _next(NULL), _coin(&Coin()){}
Currency() : _next(NULL), _prev(NULL), _position(0) {}
Coin *_coin;
Currency *_next;
Currency *_prev;
int _position;
};
/* constructor and destructor */
Exchange();
Exchange(std::string str);
~Exchange();
/* Assignment operator */
Exchange& operator =(const Exchange& copyExchange);
/* Parse Cryptsy Pairs */
friend void parseTradePairs(Currency *curr, std::string *response, int begin, int exit);
private:
std::string _exch;
Currency *_currencies;
};
这是我改变它来修复它。 typedef struct Currency
{
Currency(Coin *coin, Currency *next, Currency *prev, int position) : _coin(coin), _next(next), _prev(prev), _position(position) {}
Currency(Currency *prev, int position) : _prev(prev), _position(position), _next(NULL), _coin(&Coin()){}
Currency()
{
_next = NULL;
_prev = NULL;
_position = 0;
_coin = new Coin();
}
Coin *_coin;
Currency *_next;
Currency *_prev;
int _position;
};
答案 0 :(得分:0)
Currency
的默认构造函数是:
Currency() : _next(NULL), _prev(NULL), _position(0) {}
并且似乎没有为_coin
分配任何内存。您的Exchange::Exchange(std::string str)
构造函数也会执行:
_currencies = new Currency;
调用Currency
的默认构造函数,然后传递给parseTradePairs()
,所以最有可能是这一行:
curr->_coin->setExch(temp);
因此,尝试取消引用未初始化的指针,结果导致您的访问冲突。