試圖記住基本的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的是什麼? – nwp
顯然是錯誤的東西(見下面的回覆) – frododot