为什么构造函数调用构造函数会产生奇怪的结果?

时间:2018-12-01 13:35:42

标签: c++ oop constructor

我正在测试下面显示的代码(在c++中学习-std=c++11)。

(系统:linux,带有#include <iostream> class Point { private: double x, y; public: static unsigned int pCount; // constructor1 with no initial arguments Point() { x = 0.0f; y = 0.0f; std::cout << "Point()" << " x = " << x << " y = " << y << " point no: " << ++pCount << std::endl; } /* // constructor1 alternative: calling another constructor Point() { Point(0.0f, 0.0f); std::cout << "Point()" << std::endl; } */ // constructor2 with initial arguments Point(double cx, double cy) { x = cx; y = cy; std::cout << "Point(double, double)" << " x = " << x << " y = " << y << " point no: " << ++pCount << std::endl; } void Show() { std::cout << "Show()" << " x = " << x << " y = " << y << std::endl; } virtual ~Point() { std::cout << "~Point()" << " x = " << x << " y = " << y << " point no: " << pCount-- << std::endl; } }; unsigned int Point::pCount = 0; int main(int argc, char *argv[]) { Point p1(2.5, 7.6); Point p2; p2.Show(); p1.Show(); return (0); } 的gcc编译器)

Point(double, double) x = 2.5 y = 7.6 point no: 1
Point() x = 0 y = 0 point no: 2
Show() x = 0 y = 0
Show() x = 2.5 y = 7.6
~Point() x = 0 y = 0 point no: 2
~Point() x = 2.5 y = 7.6 point no: 1

上面的代码将输出创建为:

constructor1

但是,当我注释掉constructor1 alternative并取消注释Point(double, double) x = 2.5 y = 7.6 point no: 1 Point(double, double) x = 0 y = 0 point no: 2 ~Point() x = 0 y = 0 point no: 2 Point() Show() x = 4.64944e-310 y = 9.88131e-324 Show() x = 2.5 y = 7.6 ~Point() x = 4.64944e-310 y = 9.88131e-324 point no: 1 ~Point() x = 2.5 y = 7.6 point no: 0 时,创建的输出有点奇怪,如下所示:

constructor1 alternative

我认为在后一种情况(p2)中,将创建一个临时对象,然后将其指针传递到x。无论如何,到目前为止,一切都还不错。。。但是我坚持分配给变量yx = 0, y = 0的值:前者按预期显示x = 4.63813e-310, y = 9.88131e-324;但是,后者会吐出#include <stdio.h> int main() { FILE *opening = fopen("hello.usr", "w"); if(opening == NULL){ printf("An error occurred when opening the file!"); return 0; } else{ fprintf(opening, "Hello world!\n"); fclose(opening); printf("Writing to the file was successful.\nClosing the program.\n"); } return 0; } ,尽管值非常接近零,但对我来说还是很奇怪。

为什么后一种情况没有分配确切的“ ”值?

1 个答案:

答案 0 :(得分:2)

  

我认为在后一种情况(SELECT ROWNUM, tmp.* FROM employees tmp WHERE TO_NUMBER(ROWNUM) <= (SELECT count(*)/2 FROM employees); )中,将创建一个临时对象,然后将其指针传递给p2

您是对的,确实确实构造了一个临时建筑物,但在构造之后便将其摧毁。您可能要使用这样的委托构造函数:

constructor1 alternative

这将使用两个双精度参数调用构造函数,并且两个数据成员均被初始化。请注意,您所指的“怪异”行为不过是未初始化的数据-数据成员包含垃圾值,因为它们尚未初始化。

作为一个旁注(我意识到您说的是关于学习OOP的,所以不要太在意此话):在我看来,您的Point() : Point(0.0, 0.0) {} 类的两个坐标数据成员可以有所不同独立地。因此,您的课程不会管理不变式-在这种情况下,您可能需要考虑将类型简化为

Point

允许默认构造

struct Point { double x = 0.0; double y = 0.0; };

以及聚合初始化

Point p; // both x and y are 0.0 now

作为类界面的一部分的其他功能(打印,到另一个点的距离等)可以在自由函数中方便地定义。