2016-03-06 82 views
-1

這裏我從基類GradedActivity中創建了一個名爲Essay的派生類。我在主要被調用的對象中創建了一個Essay類的對象。當我在main()中編寫object.setGrammar(grammarPts)時,我希望能夠在setGrammar()函數的變量語法中提供分數。我究竟做錯了什麼?謝謝! 我得到一個錯誤:類繼承和使用setter和getters

99 8 F:\ lab6part3.cpp [錯誤]請求'對象'中的成員'setGrammar',它是非類類型'Essay(float,float,float,float) '

#include <iostream> 

using namespace std; 


//class gradedactivity (page 900) 
class GradedActivity 
{ 
protected: 

double score; 

public: 
//default constructor 
GradedActivity() 
{ 
score = 0.0; 
} 
//parameterized constructor 
GradedActivity(double s) 
{ 
score = s; 
} 

setScore(double s) 
{ 
score = s; 
} 

double getScore() const 
{ 
return score; 
} 

char getLetterGrade() const; 
}; 

class Essay : public GradedActivity 
{ 
private: 

float grammar; 
float spelling; 
float length; 
float content; 

public: 

Essay(float g, float s, float l, float c) 
{ 
setGrammar(g); 
setSpelling(s); 
setLength(l); 
setContent(c); 
} 

void setGrammar(float); 
float getGrammar(); 
void setSpelling(float); 
float getSpelling(); 
void setLength(float); 
float getLength(); 
void setContent(float); 
float getContent(); 
}; 

void Essay::setGrammar(float g) 
{ 
grammar = g; 
} 
float Essay::getGrammar() {return grammar;} 

void Essay::setSpelling(float s) 
{ 
spelling = s; 
} 
float Essay::getSpelling() {return spelling;} 

void Essay::setLength(float l) 
{ 
length = l; 
} 
float Essay::getLength() {return length;} 

void Essay::setContent(float c) 
{ 
content = c; 
} 
float Essay::getContent() {return content;} 

int main() 
{ 
float grammarPts; 

cout << "How many points, out of 30, did the student get for grammar?"; 
cin >> grammarPts; 

Essay object; 
object.setGrammar(grammarPts); 

return 0; 
} 
+1

你能否在你的硬盤上多付幾個字節並使用縮進? – LogicStuff

+0

在這個例子中,我沒有看到你需要繼承GradedActivity的原因。至少在代碼的和平中,沒有實際的用法。 – Joel

+0

您在'setScore'之前錯過了'void',並且'Essay'沒有生成默認的構造函數。 – LogicStuff

回答

0

這可能只是因爲您從未爲Essay定義了默認構造函數。

無論如何,我定義了一個默認構造函數,並且您的代碼運行良好,因此可能是問題所在。 https://ideone.com/yNxV8N

+1

不是默認構造不會導致UB,但會產生編譯時錯誤。 – LogicStuff

+0

不應該在沒有添加默認構造函數的情況下進行編譯。 – LogicStuff

+0

大多數編譯器會插入一個默認的構造函數,所以沒有定義一個會導致未定義的行爲,因爲你的代碼可能編譯或不編譯 – NickLamp