【发布时间】:2013-11-08 09:15:03
【问题描述】:
我有一个简单的 C++ 测试程序,可以打印出圆的属性
#include <iostream>
#include <stdlib.h>
#include "circle.h" // contains the Circle class
using namespace std;
void print_circle_attributes(float r) {
Circle* c = new Circle(r);
cout << "radius: " << c->get_radius() << endl;
cout << "diameter: " << c->get_diameter() << endl;
cout << "area: " << c->get_area() << endl;
cout << "circumference: " << c->get_circumference() << endl;
cout << endl;
delete c;
}
int main(int argc, const char* argv[]) {
float input = atof(argv[0]);
print_circle_attributes(input);
return 0;
}
当我使用参数2.4 运行程序时,它会输出:
radius: 0.0
diameter: 0.0
area: 0.0
circumference: 0.0
我之前测试过没有参数的程序,只是使用静态值,它运行得很好;所以我知道我做的课没有错……
那么我在这里做错了什么?
【问题讨论】:
-
拜托,无论教你如何使用
new,请忽略它。只写Circle c(r);,没有new,没有delete,没有指针。魔法! -
我专门使用 new 关键字是因为我想在堆上创建对象,而不是在堆栈上,它更安全,因为它没有堆栈溢出的风险(尽管单个对象不会做任何事情,但仍然)
-
#include "hidden_functions.h" // contains the Circle class(继续争论免费商店中手动内存管理的安全性。是的。这很有意义) -
提示:你对堆栈溢出的“解决方案”也比你最初“解决”的问题充满了很多更多的潜在危险。请接受 SO c++ 社区的温和鼓励,这表明您正在学习好东西:/
标签: c++ command-line-arguments argv