Yahoo奇摩知識+ 將於 2021 年 5 月 4 日 (美國東部時間) 終止服務。自 2021 年 4 月 20 日 (美國東部時間) 起,Yahoo奇摩知識+ 網站將會轉為唯讀模式。其他 Yahoo奇摩產品與服務或您的 Yahoo奇摩帳號都不會受影響。如需關於 Yahoo奇摩知識+ 停止服務以及下載您個人資料的資訊,請參閱說明網頁。
幫幫我吧~~拜託了各位.....
#include<iostream>
#include<cstdlib>
using namespace std;
int a[10]={10,60,80,52,60,70,52,96,80,40};
class grade{
public:
int a[10];
void list()
{ for(int x;x<10;x++)
cout<<a[x]<<" ";
}
};
int main()
{grade g1;
g1.list();
system("pause");
return 0;
}
為啥印不出東西阿,...我適用DevC++寫的.....聽同學說...要用建構元設定....如果真的是這樣....要怎麼寫呢??....想印出那些分數.....不懂!!!
3 個解答
- 匿名使用者2 0 年前最佳解答
class grade{
public:
int a[10];
grade(){
a[0]=10;
a[1]=60;
a[2]=80;
a[3]=52;
a[4]=60;
a[5]=70;
a[6]=52;
a[7]=96;
a[8]=80;
a[9]=40;
}
void list()
{ for(int x;x<10;x++)
cout<<a[x]<<" ";
}
};
- 匿名使用者2 0 年前
// C++
#include<iostream>
using std::cout;
using std::endl;
#include<vector>
using std::vector;
#include <ostream>
using std::ostream;
template<class T>
class Grade{
private:
vector<T> v;
public:
Grade<T>(const T* a, const int& size) : v(a, &a[size]) {}
friend ostream& operator<<(ostream& os, const Grade& g) {
for(vector<T>::const_iterator i=g.v.begin(); i!=g.v.end(); i++)
os << *i << " ";
os << endl;
return(os);
}
};
int main() {
const int a[] = {10, 60, 80, 52, 60, 70, 52, 96, 80, 40};
const Grade<int> g1(a, sizeof a/sizeof a[0]);
cout << g1;
system("pause");
return 0;
}
參考一下
:)
2005-05-06 11:48:33 補充:
嗯嗯~~
真是好人^^
- 龍Lv 72 0 年前
LinuxUser講出一個問題. 還有另一個小問題沒說. 我補充一下
你的程式有一個小問題, 不過這個小問題你犯兩次. 在C++裡, 在取用任何一個變數的值之前, 那個變數一定要有初定值. 有初定值才可取用變數的值. 不然取出的值將為亂數. 你有兩個地方都犯這小毛病… :)
1.你有兩個int的陣列都叫a. 一個是在grade這個class裡. 另一個是global. 你只設global的a的初定值為{10,60,80,52,60,70,52,96,80,40}. 所以當你宣告g1為grade的變數時, g1裡有一個int的陣列a沒有被設初定值. 因此當你呼叫g1的list時. list會顯示出a[]陣列裡的數. 既然沒初定值, a[]陣列裡的數是亂數. 所以你要在宣告g1時設定a[]的初定值. 也就是說你要在grade的建構子(元)裡設定a[]的初定值. 因為宣告g1時會呼叫grade的建構子(元)來建立g1.
2.在list這個成員函式裡, 你的for迴圈裡x沒設初定值. 所以當for迴圈比較x的值是否大於10的時候, 因x沒設初定值所以x含有亂數. 因是亂數, 所以x的值小於10的機率非常小. 而你的運氣又沒那麼好, 所以當你執行的時候, x的值不是小於10, 所以for迴圈沒執行. 因為你要把a[]裡的數顯示出來. 所以x的初定值為0.(a[0]是a[]裡的第一個數)
以下是改過的程式:
#include<iostream>
#include<cstdlib>
using namespace std;
class grade{
public:
int a[10];
grade()
{
a[0] = 10;
a[1] = 60;
a[2] = 80;
a[3] = 52;
a[4] = 60;
a[5] = 70;
a[6] = 52;
a[7] = 96;
a[8] = 80;
a[9] = 40;
};
void list()
{
int x;
for(x = 0;x<10;x++)
cout<<a[x]<<" ";
}
};
int main()
{grade g1;
g1.list();
system("pause");
return 0;
}
或者:
#include<iostream>
#include<cstdlib>
using namespace std;
int a[10]={10,60,80,52,60,70,52,96,80,40};
class grade{
public:
int a[10];
grade()
{
int x;
for(x = 0;x<10;x++)
a[x] = ::a[x];
};
void list()
{
int x;
for(x = 0;x<10;x++)
cout<<a[x]<<" ";
}
};
int main()
{grade g1;
g1.list();
system("pause");
return 0;
}
前一個程式是一個一個數來. 所以你不用global的a. 後一個是把global的a裡的數存入grade的a裡. 所以需要global的a.
這樣子你就會看到10 60 80 52 60 70 52 96 80 40啦
其餘的你老師會再教你… :)
懂不懂?不懂請再問
2005-05-06 06:18:00 補充:
▃~,喔...連stl,template,class,iterator,和de-reference都搬出來了. lol :)
怎麼好像少一個"friend operator <<"? :)
參考資料: Myself