您可以从另一个方法调用复制构造函数吗?

发布于 2024-08-16 23:38:34 字数 1590 浏览 6 评论 0原文

/** @file ListP.cpp
 *  ADT list - Pointer-based implementation. */

#include <iostream>
#include <cstddef>  // for NULL
#include <new>   // for bad_alloc
#include "ListP.h"  // header file

using namespace std;

List::List() : size(0), head(NULL)
{
} // end default constructor

List::List(const List& aList) : size(aList.size)
{
 if (aList.head == NULL)
  head = NULL; // original list is empty

 else
 { // copy first node
  head = new ListNode;
  head->item = aList.head->item;

  // copy rest of list
  ListNode *newPtr = head; // new pointer
  // newPtr points to last node in new list
  // origPtr points to nodes in original list
  for (ListNode *origPtr = aList.head->next; origPtr != NULL; origPtr = origPtr->next)
  { 
   newPtr->next = new ListNode;
   newPtr = newPtr->next;
   newPtr->item = origPtr->item;
  } // end for

  newPtr->next = NULL;
 } // end if
} // end copy constructor

void List::copy(const List& aList)
{
 List::List(aList);
} // end copy

我正在尝试创建一个名为 copy 的方法,它只调用复制构造函数。当我在 main 中测试此方法时,目标列表仍然为空。我已经单步执行了它并且执行了所有正确的行,但是当复制构造函数返回时似乎没有保存任何内容。我觉得这与范围有关,但无法查明问题所在。这是驱动程序:

#include <iostream>
using namespace std;

#include "ListP.h" 

int main ()
{
 List aList;

 ListItemType dataItem;
 aList.insert(1, 9);    
 aList.insert(2, 4); 
 aList.insert(3, 1); 
 aList.insert(4, 2); 

 List bList;
 bList.copy(aList);

 bList.retrieve(1, dataItem);
 cout << dataItem << endl;
 cout << bList.getLength() << endl;

 return 0;
}
/** @file ListP.cpp
 *  ADT list - Pointer-based implementation. */

#include <iostream>
#include <cstddef>  // for NULL
#include <new>   // for bad_alloc
#include "ListP.h"  // header file

using namespace std;

List::List() : size(0), head(NULL)
{
} // end default constructor

List::List(const List& aList) : size(aList.size)
{
 if (aList.head == NULL)
  head = NULL; // original list is empty

 else
 { // copy first node
  head = new ListNode;
  head->item = aList.head->item;

  // copy rest of list
  ListNode *newPtr = head; // new pointer
  // newPtr points to last node in new list
  // origPtr points to nodes in original list
  for (ListNode *origPtr = aList.head->next; origPtr != NULL; origPtr = origPtr->next)
  { 
   newPtr->next = new ListNode;
   newPtr = newPtr->next;
   newPtr->item = origPtr->item;
  } // end for

  newPtr->next = NULL;
 } // end if
} // end copy constructor

void List::copy(const List& aList)
{
 List::List(aList);
} // end copy

I am trying to create a method called copy that simply calls the copy constructor. When I test this method in main the target list still remains empty. I have stepped through it and all the right lines are executed, but when the copy constructor returns nothing seems to be saved. I feel this has something to do with scope, but cannot pinpoint the problem. Here is the driver program:

#include <iostream>
using namespace std;

#include "ListP.h" 

int main ()
{
 List aList;

 ListItemType dataItem;
 aList.insert(1, 9);    
 aList.insert(2, 4); 
 aList.insert(3, 1); 
 aList.insert(4, 2); 

 List bList;
 bList.copy(aList);

 bList.retrieve(1, dataItem);
 cout << dataItem << endl;
 cout << bList.getLength() << endl;

 return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

南风几经秋 2024-08-23 23:38:34

如果我理解你的问题,你就无法做你想做的事。

在调用对象上的任何其他方法之前,必须完全构造该对象(这里有一个例外,我将稍后再讨论)。此外,一个对象只能构造一次(*)。因此,当您可以调用复制方法时,该对象已经被构造,并且您不能(也不应该)再次构造它。

无法在未完全构造的对象(即构造函数尚未返回)上调用方法的一个例外是构造函数本身可以在部分构造的对象上调用方法。因此,您可以从复制构造函数调用复制方法,但反之则不然。

也就是说,如果您的对象提供了优化的交换函数,则可能会考虑一个标准技巧:

void List::copy(const List& aList)
{
    List acopy(aList);
    swap(*this, acopy);
}

这会创建 aList 的副本,然后与该副本交换对象的当前内容。当副本返回时,现在包含之前列表内容的 acopy 将被正确销毁。

最后,如果你打算这样做,当前的建议实际上是稍微调整一下并这样写:

void List::copy(List aList)
{
    swap(*this, aList);
}

在某些情况下,这可以更有效(并且永远不会降低效率)。

* - 你可以做一些奇怪的事情,并使用新的放置两次构造一个对象。但没有充分的理由这样做,而且有很多理由不这样做。

If I understand your question, you cannot do what you are trying to do.

Before you can call any other methods on an object, the object must be fully constructed (there is an exception here, I'll get back to that). Furthermore, an object can only be constructed once (*). Therefore, by the time you could call your copy method, the object would already be constructed and you can't (and shouldn't) construct it a second time.

The one exception to not being able to call a method on an object that is not fully constructed (i.e. the constructor has not yet returned) is that a constructor itself can call a method on the partially constructed object. So, you could call a copy method from the copy constructor, but not vice versa.

That said, if your object provides an optimized swap function, there is an standard trick that may be thinking of:

void List::copy(const List& aList)
{
    List acopy(aList);
    swap(*this, acopy);
}

This makes a copy of aList and then swaps the current contents of your object with this copy. acopy which now has the contents of your list before will be properly destructed when copy returns.

Finally, if you are going to do it, current recommendation is actually tweak it a bit and write it this way:

void List::copy(List aList)
{
    swap(*this, aList);
}

Under certain circumstances, this can be more efficient (and is never less efficient).

* - you can do weird things and construct an object twice with placement new. But there is no good reason to do that and many reasons why not to.

北渚 2024-08-23 23:38:34

构造函数很特殊,因为它们在对象未初始化时被调用。因此,您不能调用任何简单的函数、复制或其他函数。 C++ 需要这样做,因为它有助于编写在添加功能时更少中断的代码。

也许您想要的是将复制构造函数的主体移动到 Copy() 并从 List::List(List const&)< 调用 Copy() /代码>。

Constructors are special because they are called only when the object is uninitialized. Therefore you can't call any as simple functions, copy or otherwise. C++ requires this because it helps write code which breaks less when you add features.

Probably what you want is to move the body of the copy constructor to Copy() and call Copy() from List::List(List const&).

你的呼吸 2024-08-23 23:38:34

在您的驱动程序中,您可以

List bList;
bList.copy(aList);

调用复制构造函数

List bList(aList);

使用或

List bList = aList;

......查看您的“复制”方法:构造函数创建一个新实例。 List::copy 方法调用复制构造函数,在堆栈上创建 List 的新实例。然后它返回,并且您的新实例消失了。

您可能想要的不是“复制”方法,而是定义一个赋值运算符,

List& List::operator=(const List& aList)
{
   if (this != &aList)
   {
      // Do your copying here
   }

   return *this;
}

然后您的驱动程序可能会说

List bList;
// ...Presumably manipulate bList in some other ways in-between...
bList = aList;

“要从同一类的另一个方法中调用赋值运算符”,

*this = aList;

或者

operator=(aList);

说“我发现后者很尴尬”。但是,如果您想获取指向成员函数的指针,则可能需要通过名称显式引用运算符。

In your driver program, you have

List bList;
bList.copy(aList);

Instead, invoke the copy constructor with either

List bList(aList);

or

List bList = aList;

…Looking at your "copy" method: A constructor creates a new instance. Your List::copy method calls the copy constructor, creating a new instance of List on the stack. Then it returns, and your new instance is gone.

What you probably want instead of a "copy" method is to define an assignment operator,

List& List::operator=(const List& aList)
{
   if (this != &aList)
   {
      // Do your copying here
   }

   return *this;
}

Then your driver could say

List bList;
// ...Presumably manipulate bList in some other ways in-between...
bList = aList;

To invoke the assignment operator from inside another method of the same class, say

*this = aList;

or

operator=(aList);

I find the latter awkward. But referring to an operator explicitly by name can be necessary if you want to get a pointer to the member function.

遥远的她 2024-08-23 23:38:34

问题是,如果这样的语法如此简单,那么为什么要创建一个 copy 方法呢:> (除非你是那些想要明确说明副本的防御性人之一——那么我承认,我也是其中之一)。

您可能还对执行复制(赋值)运算符感兴趣:

List& List::operator=(const List& aList)
{
    //
}

至于无法调用复制构造函数,请参阅有关构造函数的 C++ 常见问题解答精简版。此主题也问同样的问题。

无法从类中显式调用构造函数是 C++ 标准文档的一部分,但是,maaan,您不想阅读该内容...但是;-)

The question is, if such syntax is so easy then why make a copy method at all :> (unless you're one of those defensive people who want's copies explicitly stated -- then I submit, I'm one of them too).

You may also be interested in doing a copy (assignment) operator instead:

List& List::operator=(const List& aList)
{
    //
}

As for the inability to call the copy constructor see the C++ FAQ Lite on Constructors. This thread also asks the same question.

The inability to invoke constructors explicitly from class is a part of the C++ Standard document, but maaan, you don't want to read that thing... yet ;-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文