如何在C++中使用带参数的构造函数声明具有来自另一个类的类数据的对象

How to declare an object in C++ that has a Class Data from another class with constructor with parameters

本文关键字:另一个 对象 数据 声明 构造函数 C++ 参数      更新时间:2023-10-16

我正在创建一个简单的对象。。。但是

我找不到一种"语义方式"来创建一个具有Class作为数据的带有构造函数的对象,所以我无法创建我的对象,即:

#include <iostream>
using namespace std;
class Coordinate
{
public:
    Coordinate(int axisX,int axisY) {
        x= axisX;
        y= axisY;
    }
    int x,y;
};
class Point
{
public:
    string color;
    Coordinate coordinate;
};
int main()
{
    Point myPoint; //Error here also tried Point myPoint(1,1) or myPoint::Coordenate(1,1) etc...
    return 0;
}

您必须为Point提供一个构造函数,该构造函数适当地初始化coordinate成员:

class Point
{
  //make data members private!
  string color;
  Coordinate coordinate;
public:
  Point()
    : color("red")     //initialize color
    , coordinate(4,13) //initialize coordinate
  {}
  // and/or:
  Point(int x, int y, std::string clr = "")
    : color(clr)
    , coordinate(x,y)
  {}
};

您可能需要查找构造函数初始化列表(冒号和大括号之间的部分),因为它们对您来说可能是新的。您的Coordinate构造函数也可以从初始化列表中受益:

class Coordinate
{
public:
   Coordinate(int axisX,int axisY) 
     : x(axisX), y(axisY)
   {}
private:
  //again, data members should be private in most cases
  int x,y;
};

在您的情况下,您需要在Point的构造函数中使用初始化列表,以便使用您定义的转换构造函数来构造Coordinate

class Point
{
public:
  Point()
  :
    coordinate (42, 42) // you would somehow pass these to Point's constructor
  {
  }
};

原因是Coordinate没有默认的构造函数(例如,可以在没有参数的情况下调用的构造函数)。通常,如果您没有定义默认构造函数,编译器会为您编写一个,但如果您定义任何其他构造函数,则不会发生这种情况。

您还可以通过指定默认参数将已经编写的convert构造函数修改为默认构造函数:

Coordinate(int axisX = 42, int axisY = 42) {
  x = axisX;
  y = axisY;
}

然而,我不确定这在你的程序中是否有意义。

您还可以实现Coordinate:的默认构造函数

class Coordinate
{
public:
  Coordinate ()
  :
    x (0) ,
    y (0)
  { 
  }
  // ...
};

但是,您会遇到一个问题,您可能会使用xy的有效但无意义的值实例化Coordinate对象。

可能最好的方法是我建议的第一种方法,通过修改将坐标传递给Point的构造函数:

class Point
{
public:
  Point (int x, int y)
  :
    coordinate (x, y)
  {
  }
};

这将是这样构建的:

int main()
{
  Point p(1,2);
}

现在不可能用无效或无意义的Coordinate实例化Point对象。

class Point
{
public:
point(int axisX,int axisY):Coordinate(axisX,axisY);
string color;
Coordinate coordinate;
};
相关文章: