将一个类实例返回给另一个. [英] return a class instance to another.

查看:68
本文介绍了将一个类实例返回给另一个.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况:

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

推荐答案

只需使用复制构造函数和赋值运算符.对于您的类,您可以使用编译器生成的类.但是,您必须为此删除默认的构造函数.如果要查看它们的外观...:

Just use the copy constructor and assignment operator. For your class you can get away with using the compiler generated ones. However you''d have to remove your default constructor for that. If you want to see what they''d look like...:

class A
{
    public:
       A( int n ) : n_( n ) {}
       A( const A &copy_from ): n_( copy_from.n_  ) {}
       A &operator=( const A &copy_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 &amp;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


您必须使用return *this;.

但是,您应该实现复制构造函数和赋值运算符:

You must use return *this;.

But instead you should implement copy constructor and assignment operator:

myClass& myClass::operator=(const myClass& src)
{
  number = src.number;
  return *this;
}

myClass::myClass(const myClass &src)
{
  *this = src;
}


这篇关于将一个类实例返回给另一个.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆