在C ++中,将对象作为新实例的参数传递将克隆它

时间:2019-02-13 10:41:00

标签: c++ object clone

如何在C ++中克隆对象 我测试了:

MyClass obj1;
Myclass obj2(obj1);

,并且有效。我不明白为什么。我的意思是我不理解语法。

class Duree 
{ 
public: 
Duree(int heures = 0, int minutes = 0, int secondes = 0)
 : m_heures(heures),m_minutes(minutes),m_secondes(secondes)
{}

 private: 
 int m_heures; 
 int m_minutes; 
 int m_secondes; 
 } ;



int main()  
{ 
 Duree duree1(5, 30, 47); 
 Duree duree2(duree1);
 return 0;
} 

1 个答案:

答案 0 :(得分:3)

您使用的构造是复制构造器(c'tor)。该代码由编译器自动提供。除非您自己实施,否则您将也不会看到这种情况。复制c'tor对所有成员变量执行浅表复制。这意味着一个对象中的所有值都与另一个对象中的值完全相同。

也许需要澄清一些代码

Duree( const Duree& other) {
    // this.m_heures = ...
    // get all values from one class to copy to new class
}

此示例在您的示例中被隐式调用。

如果您在语言基础方面苦苦挣扎,应该看看The Definitive C++ Book Guide and List

相关问题