0

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

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

#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;
}
4

3 回答 3

3

You have to provide a constructor for Point that does the initialization of the coordinate member appropiately:

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)
  {}
};

You might want to look up constructor initialization lists (the part between the colon and the opening brace), as they could be new to you. Your Coordinate constructor could benefit from an initialization list, too:

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;
};
于 2013-07-08T13:37:46.977 回答
1

在您的情况下,您需要在 的构造函数中使用初始化列表,Point以便Coordinate使用您定义的 convert 构造函数进行构造:

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

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

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

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

但是,我不确定这在您的程序中是否在语义上有意义。

您还可以实现一个默认构造函数Coordinate

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

但是你有一个问题,你可以用 and 的有效但无意义的值来实例化一个Coordinate对象。xy

可能最好的方法是我建议的第一个方法,并进行了修改,以便将坐标传递给Point的构造函数:

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

这将是这样构建的:

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

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

于 2013-07-08T13:34:51.697 回答
-3
class Point
{
public:
point(int axisX,int axisY):Coordinate(axisX,axisY);
string color;
Coordinate coordinate;
};
于 2013-07-08T13:39:33.467 回答