c++ - 为什么这在 C++ 构造函数中不起作用

标签 c++ inheritance constructor destructor

我正在尝试刷新我的 C++,所以我决定编写一个包含所有构造函数的类,但后来我意识到无法重用以前定义的构造函数(例如:this(arg1,arg2){},如 C#)。

所以我尝试了这个,第一个是头文件,第二个是实现文件:

头文件:

class Point
{
public:
       int get_x() const;
       void set_x(int);

       int get_y() const;
       void set_y(int);

       Point(int, int);
       Point();
       Point(const Point&);
       ~Point();
private:
        int x_coord, y_coord;

};

执行文件:

int Point::get_x() const
{
    return this->x_coord;
}
void Point::set_x(int x)
{
     this->x_coord = x;
}

int Point::get_y() const
{
    return this->y_coord;
}
void Point::set_y(int y)
{
     this->y_coord = y;
}

Point::Point(int x, int y)
{
  this->set_x(x);
  this->set_y(y);
}

Point::Point(const Point& p)
{
  Point(p.get_x(), p.get_y());
}

// class constructor
Point::Point()
{
  Point(0, 0);
}

// class destructor
Point::~Point()
{
    // insert your code here
}

然后在 main.cpp 中我这样做:

int main(int argc, char *argv[])
{

    Point a = Point(2, 3);
    Point b = Point(); 
    Point c = Point(a);

    system("PAUSE");
    return EXIT_SUCCESS;
}

只有“a”对象被正确初始化,但其他两个对象具有这些随机值并且没有按照我希望的方式进行初始化。

最佳答案

这两行

Point(p.get_x(), p.get_y());

Point(0, 0);

不要做你认为他们做的事:他们不是在被初始化的对象上调用相应的构造函数,而是创建一个新的、不相关的临时对象,该对象会立即被丢弃。正在创建的 Point 的成员保持未初始化状态。

您可以通过定义一个进行初始化的私有(private)函数来解决这个问题。如果您可以使用现代 C++ 编译器,您还可以使用 C++11 标准:它允许您 "chain" constructors .

关于c++ - 为什么这在 C++ 构造函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24555024/

相关文章:

c++ - 派生类构造函数内部如何调用基类构造函数

java - Java构造函数和线程安全

c++ - 虚基类的构造函数参数

c++ - 什么数据类型用于存储文件名和文件大小?

c++ - 如何使用运算符编写可继承的模板类

iphone - 在 iPhone 应用程序中使用 C++ 结构

java - 将内核模型传输到 Java 中的输出模型

iphone - 来自父类(super class)的重写属性

c++ - 理解 C++ 中文件 I/O 的指针

c++ - 为什么boost asio中的async_read将const MutableBufferSequence作为第二个参数?