如何在C++的类中有效地使用方法

How do you effectively use methods within classes in C++?

本文关键字:有效地 使用方法 C++      更新时间:2023-10-16

我正在做一个家庭作业,涉及编写一个程序来绘制带有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 字符数组,用于保存形状的 ASCII 字符,displayShape 是一个打印出该 2D 数组的函数。 正如我上面所说,drawCircle函数有效,但moveCircle方法不起作用。 当我尝试在moveCircle中使用它时,我是否称drawCircle方法为错误。

void drawCircle();

这不是函数调用;它是一个函数原型声明。 要调用该函数,只需使用

drawCircle();
函数

原型只是告诉编译器存在具有特定签名的函数。 这允许您执行类似操作(尽管以这种方式执行此操作并不常见(。

int main() {
    void Foo();
    Foo();
}
void Foo { /* whatever */ }

如果省略原型,编译器将抛出错误,因为Foo在使用之前未声明。 在类似(和更常见(的脉络中,您也可以这样做(称为前向声明(。

void Foo();
int main() {
    Foo();
}
void Foo { /* whatever */ }

或者只是先声明它,但你通常不需要在main之前有大量的功能。

void Foo { /* whatever */ }
int main() {
    Foo();
}