l******d 发帖数: 530 | 1 volume 1, 2nd edition, p. 719 -720
对下面代码不是很懂。
IntStack只有一个constructor
IntStack() : top(0) {}
没有parameter,那么这句
IntStackIter(IntStack& is) : s(is), index(0) {}
initializer list里s(is)是怎么被调用的?(s是IntStack类型的reference)
书中代码如下:
//: C16:IterIntStack.cpp
// Simple integer stack with iterators
//{L} fibonacci
#include "fibonacci.h"
#include "../require.h"
#include
using namespace std;
class IntStack {
enum { ssize = 100 };
int stack[ssize];
int top;
public:
IntStack() : top(0) {}
void push(int i) {
require(top < ssize, "Too many push()es");
stack[top++] = i;
}
int pop() {
require(top > 0, "Too many pop()s");
return stack[--top];
}
friend class IntStackIter;
};
//////////////// An iterator is like a "smart" pointer:
class IntStackIter {
IntStack& s;
int index;
public:
IntStackIter(IntStack& is) : s(is), index(0) {}
int operator++() { // Prefix
require(index < s.top,
"iterator moved out of range");
return s.stack[++index];
}
int operator++(int) { // Postfix
require(index < s.top,
"iterator moved out of range");
return s.stack[index++];
}
}; | l*********s 发帖数: 5409 | 2 What do you mean? it is initialization,right?
【在 l******d 的大作中提到】 : volume 1, 2nd edition, p. 719 -720 : 对下面代码不是很懂。 : IntStack只有一个constructor : IntStack() : top(0) {} : 没有parameter,那么这句 : IntStackIter(IntStack& is) : s(is), index(0) {} : initializer list里s(is)是怎么被调用的?(s是IntStack类型的reference) : 书中代码如下: : //: C16:IterIntStack.cpp : // Simple integer stack with iterators
| l******d 发帖数: 530 | 3 哦,我没仔细看,s是reference to IntStack,不是IntStack,所以s(is)是用is来初
始化s,是这么理解吧?
如果s是pointer to IntStack,is也是个pointer to IntStack,这么也行,对吧
【在 l*********s 的大作中提到】 : What do you mean? it is initialization,right?
| l*********s 发帖数: 5409 | | b********r 发帖数: 1080 | 5 这不是缺省的copy constructor吗?
【在 l******d 的大作中提到】 : 哦,我没仔细看,s是reference to IntStack,不是IntStack,所以s(is)是用is来初 : 始化s,是这么理解吧? : 如果s是pointer to IntStack,is也是个pointer to IntStack,这么也行,对吧
|
|