在另一个C ++类中创建一个对象(Creating an object within another class C++)

编程入门 行业动态 更新时间:2024-10-26 12:31:24
在另一个C ++类中创建一个对象(Creating an object within another class C++)

我得到一个奇怪的运行时错误,我根本无法理解。 我正在创建我的类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) { }

更多推荐

本文发布于:2023-04-28 00:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329216.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:创建一个   类中   对象   class   object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!