我一直在努力理解默认构造函数,如果它是类中唯一的构造函数,我想我就明白了。但是,如果我在类中定义了多个构造函数怎么办。我想做的是创建一个类“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/