问题描述
我的情况:
My situation:
class myClass()
{
public: myClass(void);
myClass getMyClass();
int number;
};
myClass::myClass()
{
number=0;
}
myClass myClass::getMyClass(){
//what should i do here so that i can copy the class a to class b
//when i use b=a.getMyClass();
//i try return myClass() but it return the default constructor.
}
int main(){
myClass a,b;
a.number=5;
b=a.getMyClass();
cout<<b.number;
}
推荐答案
class A
{
public:
A( int n ) : n_( n ) {}
A( const A ©_from ): n_( copy_from.n_ ) {}
A &operator=( const A ©_from )
{
A temp( copy_from );
std::swap( n_, temp.n_ );
return *this;
}
friend std::ostream &operator<<( std::ostream &str, const A &a )
{
return str << a.n_;
}
private:
int n_;
};
int main()
{
A a( 5 ), b( 4 );
std::cout << a << std::endl << b << std::endl;
// Look ma, no special syntax needed!
a = b;
std::cout << a << std::endl << b << std::endl;
}
请注意,赋值运算符要复杂一些-我倾向于像这样写它们,以使当类变得更加复杂时可以使它们保持异常安全.
为了回应以下Volodya的评论...
赋值运算符的复制和交换"样式的另一个好处是,您无需检查自我赋值.如果您查看较旧的C ++文本(1999年前后,这个成语用作Tom Cargill的"aaarrggghhh,例外打破了一切!"挑战的解决方案的一部分),您将看到这样写的赋值运算符:
Note that the assignment operator is a bit more complicated that it needs to be - I tend to write them like that these days to keep them exception safe when the class gets more complicated.
In response to Volodya''s comment below...
Another benefit of the "copy and swap" style of assignment operator is that you don''t need to check for self assignment. If you look at older C++ texts (pre-1999 or so when the idiom was used as part of the solution to Tom Cargill''s "aaarrggghhh, exceptions break everything!" challenge) you''ll see assignment operators written like this:
A &operator=( const A ©_from )
{
if( ©_from != this )
{
n_ = copy_from.n_;
}
return *this;
}
这里的想法是确保当您与指针成员打交道时,不要做类似以下的愚蠢的事情:
The idea here was to make sure that when you''re dealing with pointer members and you don''t do something daft like:
A a( 10 );
a = a;
您不会导致内存泄漏,也不会导致重复引用一个对象或一个删除的对象. (这很可能是通过别名发生的,我们当中没有多少人愚蠢到可以直接做到).
复制和交换删除了该要求.如果遵循该代码,将会看到所有数据都首先被复制,这涉及分配和复制新的子对象.在将对象的旧内容与临时对象交换之后,临时对象的析构函数将从原始对象中清除所有子对象.因此,复制步骤处理分配新的子对象,交换步骤处理释放旧的子对象.
干杯,
Ash
you won''t cause a memory leak or end up double referencing an object or a deleted object. (It''s more likely this will happen through through an alias, not many of us are daft enough to do it directly).
Copy and swap removes that requirement. If you follow the code you''ll see that all data is copied first which deals with allocating and copying new sub-objects. After the old contents of the object are swapped with the temporary the temporary''s destructor cleans up any sub objects from the original object. So the copy step handles allocating new sub objects, the swap step handles freeing old sub objects.
Cheers,
Ash
myClass& myClass::operator=(const myClass& src)
{
number = src.number;
return *this;
}
myClass::myClass(const myClass &src)
{
*this = src;
}
这篇关于将一个类实例返回给另一个.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!