![](/img/trans.png)
[英]How to initalize nested class members in outer class constructor in C++
[英]In C++, how can I use a nested class type in an other nested class (the two nested classes are under the same outer class)
我有一個List
類,它有兩個嵌套類: ListItem
和ListIterator
。 在ListIterator
類中,我有一個ListItem
類型的屬性。 在頭文件“List.h”我所定義的ListItem
的類的私有屬性ListIterator
,它完全編譯。 但是,在“List.cpp”文件,當我嘗試定義的構造函數ListIterator
它給我的錯誤:
List.cpp: In constructor ‘List::ListIterator::ListIterator(bool)’:
List.cpp:24:46: error: no matching function for call to ‘List::ListItem::ListItem()’
List::ListIterator::ListIterator(bool reverse){
^
List.cpp:24:46: note: candidates are:
List.cpp:7:1: note: List::ListItem::ListItem(void*)
List::ListItem::ListItem(void* data){
^
List.cpp:7:1: note: candidate expects 1 argument, 0 provided
In file included from List.cpp:1:0:
List.h:2:8: note: List::ListItem::ListItem(const List::ListItem&)
class ListItem {
^
List.h:2:8: note: candidate expects 1 argument, 0 provided
這是我的 List.h 文件:
class List{
class ListItem {
public:
ListItem(void*);
void* getData();
ListItem* getNext();
ListItem* getPrev();
private:
void* data;
ListItem* next;
ListItem* prev;
};
class ListIterator {
public:
ListIterator(bool);
bool hasNext();
void* next();
private:
bool reverse;
ListItem current;
};
public:
List();
~List();
long getSize();
int addData(void*);
void* remove(long);
long indexOf(void*);
ListIterator* cellAt(long);
ListIterator& iterator(bool);
private:
long size;
ListItem head;
ListItem tail;
};
這是我的 List.cpp 文件:
#include "List.h"
#include <iostream>
using namespace std;
/* ListItem */
List::ListItem::ListItem(void* data){
this->data = data;
}
void* List::ListItem::getData(){
return this->data;
}
List::ListItem* List::ListItem::getNext(){
return this->next;
}
List::ListItem* List::ListItem::getPrev(){
return this->prev;
}
/* ListIterator */
List::ListIterator::ListIterator(bool reverse){
this->reverse = reverse;
}
bool List::ListIterator::hasNext(){
return false;
}
void* List::ListIterator::next(){
return NULL;
}
您的問題不在於類嵌套,而在於成員初始化。
在構建ListIterator
您也在構建其成員,因此是ListItem
,然后您需要為其指定一個ctor調用,因為它具有一個用戶定義:
List::ListIterator::ListIterator(bool b) : current(something) {
...
}
這是表達如何初始化current
的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.