假设我有一个名为 的类MyClass,它有两个成员变量(都被int)称为firstNumber_和secondNumber_。这个类还有一个被调用的方法clone( ),它创建一个具有相同值的对象的新实例并返回该新实例。
问题是,当返回一个新的类实例时,我是把它作为指针、引用还是只是实例本身返回?
// MyClass.h
class MyClass {
private:
int firstNumber_;
int secondNumber_;
public:
MyClass( int numA, int numB ) {
firstNumber_ = numA;
secondNumber_ = numB;
}
~MyClass( ) { };
// This method creates a copy of the object and returns that object.
// The ( ? ) is there because I am not sure what type the returned value is.
MyClass ( ? ) clone( ) {
// Do I just return the new instance? Or do I need to return a reference or a pointer of the new instance?
return MyClass( firstNumber_, secondNumber_ );
}
};
实现这一目标的正确方法是什么?请注意,MyClass它不会从任何其他类继承。
提前致谢。