【发布时间】:2014-06-14 21:43:35
【问题描述】:
尝试记住基本的 C++ 内容(已经很久了),并尝试使用编译器。我创建了一个简单的基/子继承示例。
我希望下面的输出
index 0 is 0
index 1 is 1
index 2 is 2
而是得到:
index 0 is 0
index 1 is 2
index 2 is 0
有人能指出我的明显错误吗?
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
class Base
{
public:
Base(){x=0;}
int x;
};
class Derived : public Base
{
public:
Derived() { y=0;}
int y;
};
// practicing operator definition syntax
ostream& operator<<(ostream& ostr, const Base& base)
{
ostr << base.x << endl;
ostr << flush;
return ostr;
}
void init(Base *b)
{
for (int i = 0; i<3; i++)
{
b[i].x=i;
}
};
int main(int argc, char** argv)
{
Derived arr[3];
init(arr);
for (int idx = 0; idx< 3; idx++)
{
cout << "index is " << idx << ' ' << arr[idx] << endl;
}
return 0;
}
【问题讨论】:
-
你要传递什么给
init? -
显然是错误的事情(见下面的回复)
标签: c++ inheritance