如何在C++的类中有效地使用方法
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 字符数组,用于保存形状的 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();
}
相关文章:
- 有效地使用std::unordered_map来插入或增加键的值
- 如何有效地使用 std::async 对指针数组执行操作
- 为什么优先级队列是使用堆实现的,而我们可以更有效地使用向量来实现它
- 为什么 std::unordered_map 很慢,我可以更有效地使用它来缓解这种情况吗?
- 如何在处理传统C字符串的C样式函数中有效地使用std::string
- 如何在C 中更有效地使用
- 如何有效地使用C++11随机生成器
- 在C++中有效地使用继承
- 如何有效地使用载体
- 我是否最有效地使用 SSE 资源
- 如何有效地使用结构定义,包括来自另一个源文件的运算符
- 如何在特征中有效地使用逆和行列式
- 更有效地使用fork()和写时复制内存共享
- 有效地使用多个分配器
- 在不使用“protected”的情况下,子类如何有效地使用基类中定义的变量
- 有效地使用python对象来迭代调用python函数的大型数据集
- 如何有效地使用std::线程来减少运行时间
- 如何在C++中有效地使用字符串data_type
- 如何有效地使用std::atomic
- 如何在C++的类中有效地使用方法