[英]How do you effectively use methods within classes in C++?
我正在做一項作業,其中涉及編寫一個程序來繪制帶有ASCII字符的形狀並將它們在屏幕上移動。 在此示例中,我試圖編寫一種方法來移動已經繪制的圓。 我知道我的drawCircle
方法有效,但是當我嘗試在moveCircle
方法中調用drawCircle
方法時,它不會輸出任何內容。
void CircleType::drawCircle() const{
for (int i = 0; i < NUMBER_OF_ROWS; i++) {
for(int j = 0; j < NUMBER_OF_COLUMNS; j++) {
int p = abs (x - j);
int q = abs (y - i);
int distance = pow(p, 2) + pow(q, 2);
int realDistance = pow(radius, 2);
if (abs(realDistance - distance) <= 3){ // I tested out several values here, but 3 was the integer value that consistently produced a good looking circle
drawSpace[i][j] = symbol;
}
}
}
displayShape();
return;
}
bool CircleType::moveCircle(int p, int q){
if (p - radius < 0 || p + radius > NUMBER_OF_COLUMNS){
cout << "That will move the circle off the screen"<< endl;
return false;
}
else if (q - radius < 0 || q + radius > NUMBER_OF_ROWS){
cout << "That will move the circle off the screen"<< endl;
return false;
}
else{
x = p;
y = q;
for (int m = 0; m < NUMBER_OF_ROWS; m++){
for(int n = 0; n < NUMBER_OF_COLUMNS; n++){
if (drawSpace[m][n] == symbol)
drawSpace[m][n] = ' ';
}
}
void drawCircle();
return true;
}
}
drawSpace
是一個2D char數組,其中保存該形狀的ASCII字符,而displayShape
是一個打印該2D數組的函數。 就像我在上面說的, drawCircle
函數有效,但是moveCircle
方法無效。 當我嘗試在moveCircle
使用drawCircle
方法時,是否將其moveCircle
錯誤方法?
void drawCircle();
那不是函數調用; 它是一個函數原型聲明。 要調用該函數,只需使用
drawCircle();
函數原型只是告訴編譯器存在具有特定簽名的函數。 這樣,您就可以做這樣的事情(盡管這種做法根本不常見)。
int main() {
void Foo();
Foo();
}
void Foo { /* whatever */ }
如果省略原型,則編譯器將引發錯誤,因為在使用Foo
之前未聲明Foo
。 同樣(更常見),您也可以執行此操作(稱為前向聲明)。
void Foo();
int main() {
Foo();
}
void Foo { /* whatever */ }
或者只是先聲明它,但通常在main
之前不需要大量函數。
void Foo { /* whatever */ }
int main() {
Foo();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.