如何使用在另一个类的构造函数中的堆栈上接受参数的构造函数创建对象

How to create an object using a constructor that takes arguments on stack in constructor of another Class

本文关键字:构造函数 参数 创建对象 堆栈 另一个 何使用      更新时间:2023-10-16

请考虑以下代码:

----·

class A{
    private:
        char* mStr;
    public:
        A(const char* str);
        ~A();      
}

---- A.cpp

A::A(const char* str) 
{
    mStr = new char[MAX_SIZE];
    strncpy(mStr,str,MAX_SIZE);
}
A::~A() 
{
}

----

·
class B{
    private:
        A myA;
    public:
        B();
        ~B();      
}

---- B.cpp

B::B() 
{
    myA = A("aaa");
}
B::~B() 
{
}

现在的问题是编译器抛出错误:错误:调用"A::A()"没有匹配函数

我想避免使用指针,如果可能的话,我希望在堆栈上使用 myA。如果我在 b.h 中的声明期间传递参数,那么编译器也会抛出错误。创建这样的对象的方法是什么?

一种可能的方法是使用初始值设定项列表:

B::B(const char* str) : myA("aaa")
{
}

在您的示例中,A 的构造函数没有考虑到需要为其私有成员分配内存,因此如果您不修复它,它可能会崩溃。但是您的问题应该用上面的语法来解决。

当你定义一个接受某些参数的构造函数时,你不在乎它们是如何提供的或它们来自哪里(好吧,对于像 int 这样简单的东西,你不需要)。举个例子

  Point::Point( int x, int y )

如果调用者希望使用另一个对象中包含的值,则由他来获取并提供它们 - 但这绝对与你如何编写构造函数无关。所以他会像这样调用上面的构造函数:

  Point apoint( 1, 2 );

//或: Point apoint( anObj.GetX() and Obj.GetY() );或: Point apoint ( anObj.GetX(), anOtherObj.Y );与 Lines 构造函数一起使用的语法用于传递参数以太该类的成员或该类的基类 - 在您的情况下可能是成员。为了给你一个提示,这里会有一些很好的 Line 类构造函数,假设你的点类有自己的一组很好的构造函数 - 如果没有,请添加它们!

  class Line
  {
  public:
      Line( const Point& p1, const Point&p1 )
      : m_Point1(p1), m_Point2(p2)
      {}
      Line( int x1, int y1, int x2, int y2) 
      : m_Point1(x1, yx), m_Point2(x2, y2)
      {}
  private:
      Point m_Point1;
      Point m_Point2;
  };

这样称呼:

  Point aPoint, bPoint;
  .
  .
  Line aline( aPoint, bPoint );
  Line bline( 1, 1, 2, 2 );
class B{
    private:
        A myA;
    public:
        B();
        ~B();      
}

在此类中,当您使用 A myA 时,这意味着构造函数将创建一个类 A 的对象。但在A myA意味着它将调用未定义的构造函数A()

根据我的建议,您可以将myA声明为 A* myA,在构造函数 B 中您可以使用new myA("aaa")如下所示。

B::B(const char* str) 
{
    myA = new A("aaa");
}