2013-10-16 32 views
0

Java(Works)在C++中實現簡單的Java程序(抽象類)

抽象類Personnell具有Manager和Worker的子類。 getAnnualIncome()是抽象函數。

Personnell employee[] = 
{ 
    new Manager("Thomas", "Nasa", 1337, 250000), 
    new Worker("Simon", "Netto", 1336, 6.98, 36) 
}; 
System.out.println("Name\t\tAnnual Income"); 
for (int i = 0; i < employee.length; i++) 
{ 
System.out.printf(employee[i].getName() + "\t\t£%.2f%n", employee[i].getAnnualIncome()); 
} 

C++(不工作)

Personnell employee[] = 
{ 
    Manager ("Tom", "Ableton", 1234, 400000), 
    Worker ("Simon","QuickiMart", 666, 40, 3.50) 
}; 

cout << "Name\t\tJob\t\tAnnual Income"<< endl<<endl; 
for (int i = 0; i < 3; i++) 
{ 
    cout << employee[i].getName() << "\t\t"<< employee[i].getDept()<<"\t\t"<< employee[0].getAnnualIncome() << endl; 
} 

錯誤:抽象類 「Personnell」 的陣列是不允許的: 函數 「Personnell :: getAnnualIncome」 是一個純虛擬函數

試過與指針有關的一些不同的事情,但我仍然需要我的頭。 謝謝,湯姆

編輯(添加的定義和說明) Personnell具有

virtual double getAnnualIncome()=0; 

Manager具有

double getAnnualIncome(); //declaration 
double Manager::getAnnualIncome() //definition 
{ 

return this->salary_; 
} 

工人有

double getAnnualIncome(); //declaration 
double Worker::getAnnualIncome() //definition 
{ 
return (this->hourlyRate_ * this->hoursPerWeek_)*52; 
} 

做什麼AJB說,輸出是:

名工作年收入

湯姆的Ableton 400000

西蒙QuickiMart 400000 //應該是7280

+0

您是否也可以添加類的定義和實現? – Hurzelchen

+0

你是否在'Manager'和'Worker'中重寫'Personnell :: getAnnualIncome'? – yamafontes

+0

我還沒有嘗試過,但是...嘗試將'Personnell employee [] ='更改爲'Personnell * employee [] =',在數組中的'Manager'和'Worker'之前放置一個'new'員工的值,並將'employee [i] .getName()'更改爲'employee [i] - > getName()'[以及其他字段的值]。你不能擁有一組'Personnell'對象,因爲這是抽象的,編譯器不會知道每個數組元素有多大。這就是爲什麼你需要指針。附:我不是C++專家,所以我不能保證我有正確的答案。 – ajb

回答

0

您不能有一個Personnell對象的數組,因爲Personnell是一個抽象類型,編譯器不會知道每個數組元素有多大。所以你需要使用指針。 (它的工作原理在Java中,因爲實際上,Java的自動使用指針。)

更改employee定義

Personnell *employee[] = 
{ 
    new Manager ("Tom", "Ableton", 1234, 400000), 
    new Worker ("Simon","QuickiMart", 666, 40, 3.50) 
}; 

,取而代之的

cout << employee[i].getName() << "\t\t"<< employee[i].getDept()<<"\t\t"<< employee[0].getAnnualIncome() << endl; 

使用->因爲employee[i]現在是一個指針:

cout << employee[i]->getName() << "\t\t"<< employee[i]->getDept()<<"\t\t"<< employee[i]->getAnnualIncome() << endl; 

(The最後employee[0]是錯字,應更改爲employee[i]; for (int i = 0; i < 3; i++)由於陣列中只有兩個元素而看起來很像打字錯誤。)

0

在C++中,當你創建一個基類對象的類型的數組,一些所謂的對象切片發生:即,當您聲明一個抽象類的數組並且將子類放入其中時,僅存儲抽象部分(即純虛擬)。正如你所看到的,你不能調用純虛函數,因爲employee數組中的對象是切片對象。