我得到一个奇怪的运行时错误,我根本无法理解。 我正在创建我的类Circle的对象,它具有以下默认构造函数:
Circle::Circle() { this->radius = 0; this->center->setX(0); this->center->setY(0); }正在初始化的变量是:
private: double radius; Point *center; };当我尝试创建类圈的对象时,我收到运行时错误。 现在我只在动态声明Point对象时才会出现此错误。 我的语法有什么问题吗? 当我在我的Circle类中声明Point时,改为:
Point center;并将其初始化为:
Circle::Circle() { this->radius = 0; this->center.setX(0); this->center.setY(0); }有用。 为什么在动态创建对象时会出现这些错误? 我可以不像第一个例子中那样使用两个“ - >”吗?
这是我的第一篇文章,我希望这不是一个太愚蠢的问题。 提前致谢。
I'm getting a strange runtime error that I simply cannot comprehend. I'm making an object of my class Circle, which has the following default constructor:
Circle::Circle() { this->radius = 0; this->center->setX(0); this->center->setY(0); }The variables that are being are initialized are:
private: double radius; Point *center; };When I try to make an object of the class circle, I get a runtime error. Now I only get this error when the Point objectis declared dynamically. Is there anything wrong with my syntax? When I declare the Point in my Circle class like this instead:
Point center;And initializes it like this instead:
Circle::Circle() { this->radius = 0; this->center.setX(0); this->center.setY(0); }It works. Why do I get these errors when I create the object dynamically? Can I not use two "->" like in the first example?
This is my first post, I hope this is not a too stupid question. Thanks in advance.
最满意答案
你应该更好地使用
Circle { private: double radius; Point center; // <<<<<<< No pointer here };你不需要指针。
当前代码的问题是没有为指针变量分配内存。 我也不建议这样做(例如使用center = new Point() )。 如上所述,没有必要。
此外,您不需要此 - this->来访问类成员。 只需在构造函数中使用成员初始化列表:
Circle::Circle() : radius(0), center(0,0) { }You should better use
Circle { private: double radius; Point center; // <<<<<<< No pointer here };You don't need a pointer.
The problem with your current code is that no memory is allocated for your pointer variable. I'd also not recommend to do it (e.g. with center = new Point()). As mentioned, it's not necessary.
Also you don't need this-> to access class members. Just use the member initializer list in your constructor:
Circle::Circle() : radius(0), center(0,0) { }更多推荐
发布评论