【发布时间】:2017-11-23 22:43:25
【问题描述】:
晚上好(感恩节快乐),
我有以下代码(从我的主代码中提取到一个独立文件中)并且收到了一些我想解决的警告消息。
代码如下:
#include <cassert>
#include <ostream>
#include <climits>
#include <iostream>
#include <string>
using namespace std;
class WordCount
{
public:
// Constructors
WordCount() : word(""), count(0) { }
WordCount(string theWord, unsigned theCount = 1) : word(theWord), count(theCount) { }
// Accessors
string Word() const { return word; }
unsigned Count() const { return count; }
// Mutator
void Update() { ++count; }
// Output a Word to a stream.
void Show(ostream &os) { os << word << "=" << count; }
// Overloaded relational operators
bool operator<(WordCount &rhs) { return word < rhs.word; }
bool operator>(WordCount &rhs) { return word > rhs.word; }
bool operator==(WordCount &rhs) { return word == rhs.word; }
bool operator<=(WordCount &rhs) { return word <= rhs.word; }
bool operator>=(WordCount &rhs) { return word >= rhs.word; }
bool operator!=(WordCount &rhs) { return word != rhs.word; }
private:
string word; // The word to be counted
unsigned count; // The number of occurrences
};
class Queue
{
private:
struct Node
{
WordCount data; //data in node
Node *next; //pointer to next node
// Default Constructor
Node() : next(0) {}
// Explicit Constructor
Node(const WordCount &theData, Node *const theNext = 0)
: data(theData), next(theNext) { }
};
public:
Queue() : head(0), tail(0) {}
bool Empty() const { return head == 0; }
void Enqueue(const WordCount &elem);
WordCount Dequeue();
WordCount Head() { return head->data; }
private:
Node *tail; // "end" of queue
Node *head;
};
void Queue::Enqueue(const WordCount &elem)
{
Node* temp = new(nothrow) Node(elem);
assert(temp != NULL);
// head == tail if head == NULL, so must also be assigned temp
if (head == NULL)
head = temp;
// add temp after current tail
else
tail->next = temp;
// update tail adress to be new temp node
tail = temp;
}
WordCount Queue::Dequeue()
{
assert (!Empty());
WordCount poppedData = head->data;
Node *temp = head;
head = head->next;
if (head == NULL)
tail = NULL;
delete temp;
return poppedData;
}
int main()
{
return 0;
}
当我执行 g++ test.cpp -Wall 时,我收到以下警告
test.cpp: In constructor 'Queue::Queue()':
test.cpp:61:8: warning: 'Queue::head' will be initialized after [-Wreorder]
Node *head;
^
test.cpp:60:8: warning: 'Queue::Node* Queue::tail' [-Wreorder]
Node *tail; // "end" of queue
^
test.cpp:54:2: warning: when initialized here [-Wreorder]
Queue() : head(0), tail(0) {}
有没有办法让我重写/重新排列代码以保持其功能并删除这些警告?我完全不熟悉这个警告,并且一直在阅读它,但是很多代码示例对我来说很难理解,更不用说理解解决它的方法了。
任何建议将不胜感激,谢谢。
【问题讨论】:
标签: c++ class initialization warnings