c++ - 具有类 c++ 的普通构造函数的默认构造函数

标签 c++ class constructor default-constructor

我一直在努力理解默认构造函数,如果它是类中唯一的构造函数,我想我就明白了。但是,如果我在类中定义了多个构造函数怎么办。我想做的是创建一个类“vector ”,它将存储二维 vector 。我需要一个构造函数来将坐标设置为主函数中给定的值。我还需要一个默认构造函数,它在调用时会将坐标设置为 0。我似乎无法弄清楚如何使两者在同一代码中工作

#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <algorithm>

using namespace std;

class Vector {
    double x_coord, y_coord;
public:
Vector(double x_coord=0, double y_coord=0); //default contructor???

Vector (double x, double y) //normal constructor
{
    set_values (x,y);
}
void set_values(double new_x, double new_y) //function to set values for the vectors
    {
        x_coord=new_x;
        y_coord=new_y;
    }
   double get_x()
    {
        return x_coord;
    }
   double get_y()
    {
        return y_coord;
    }

};

最佳答案

我可以想象使用以下方法构造类的对象:

Vector v1;         // Construct with x = 0, y = 0
Vector v2(10);     // Construct with x = 10, y = 0
Vector v3(10, 20); // Construct with x = 10, y = 20

您可以只用一个构造函数完成所有这些:

Vector(double x=0, double y=0) : x_coord(x), y_coord(y) {}

您不需要第二个构造函数。

关于c++ - 具有类 c++ 的普通构造函数的默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34551974/

相关文章:

安卓开发::查看对象

c++ - 首次使用对象后调用的全局对象构造函数

c# - 如何使此类通用? (.NET C#)

javascript - 如何从 Javascript 类构造函数中访问分配给对象的变量名称?

java - BackgroundSubtractorMOG2 中的 "history"是什么意思?

c# - 在构造类的新实例时,如何避免传递对父对象的引用?

c++ - 获取临时地址 - 需要解决方法

python - 测试 Python 类中的特定方法

c++ - 为什么基于指针交换两个值在函数范围之外不起作用?

c++ - 如何从目标读取参数