我昨天遇到了一个错误,虽然它很容易解决,但我想确保我正确理解C++.
我有一个受保护成员的基类:
class Base
{
protected:
int b;
public:
void DoSomething(const Base& that)
{
b+=that.b;
}
};
Run Code Online (Sandbox Code Playgroud)
这编译并且工作得很好.现在我扩展Base但仍想使用b:
class Derived : public Base
{
protected:
int d;
public:
void DoSomething(const Base& that)
{
b+=that.b;
d=0;
}
};
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下DoSomething仍然参考a Base,而不是Derived.我希望我仍然可以访问that.b内部Derived,但我得到一个cannot access protected member错误(MSVC 8.0 - 还没有尝试过gcc).
显然,添加一个公共getter b解决了这个问题,但我想知道为什么我无法直接访问b.我认为,当您使用公共继承时,受保护的变量对派生类仍然可见.
是否有一个标准来访问的底层容器的方式stack,queue,priority_queue?
我发现了一个叫方法:_Get_container()在VS2008实施stack和queue,但没有一个priority_queue!我认为它不是标准的.
另外,我知道这是一个愚蠢的问题!我在哪里可以找到标准库的官方文档?
仅仅为了澄清,我并没有试图弄乱底层容器.我试图做的就是:
template <class Container>
std::ostream& printOneValueContainer(std::ostream& outputstream, Container& container)
{
Container::const_iterator beg = container.begin();
outputstream << "[";
while(beg != container.end())
{
outputstream << " " << *beg++;
}
outputstream << " ]";
return outputstream;
}
// stack, queue
template
< class Type
, template<class Type, class Container = std::deque<Type> > class Adapter
>
std::ostream& operator<<(std::ostream& outputstream, const Adapter<Type>& adapter) …Run Code Online (Sandbox Code Playgroud) 在c ++中,如何打印出堆栈的内容并返回其大小?
std::stack<int> values;
values.push(1);
values.push(2);
values.push(3);
// How do I print the stack?
Run Code Online (Sandbox Code Playgroud)