简体   繁体   中英

Copy Object of one class to object of another class…noob

I am trying to let user choose on which class to perform function() on. Say there are 2 classes with objects A and B Function uses functions like obj.get and obj.set. I want to choose between A and B and copy that to obj.

Is there a way to do it. Problems : A=Obj....not working If I use Switch case or any loop, and declare Obj as object of chosen class, problem with scope.

Please help !! Both classes have exact same variables and methods.

If both objects A and B are of the same class just do it like this:

(Indeed the if A and B have exactly the same fields and methods the should belong to the same class, if it's a real program)

MyClass A,B;
//...
A = copy(B);
/*
 * 
 * 
 * 
 * 
 */
MyClass copy(MyClass arg) {
    MyClass result = new MyClass();
    result.field1 = arg.field1;
    result.field2 = arg.field2;
    //........
    return result
}

Or override the clone method in MyClass . Note: Most people agree that Java's clone is broken.You may read more discussion on the topic in Effective Java 2nd Edition , Item 11: Override clone judiciously. He recommends instead to use a copy constructor or copy factory.

I see you tagged java and C++, which one are you using?

Your statement is hard to understand, but if I'm correct, you have something like:

ClassA A = new ClassA()
ClassB B = new ClassB()

And you want to copy something from obj A to obj B? Use this:

B.set(A.get());

if you are using C++ then u can identify the name of the class by doing this,

 #include <typeinfo>.
..
..
..
.
cout << typeid(objA).name() << endl;

I believe you are having problems identifying the class based on user's input... In that case the typeid would work. Just check which class the user has selected and based on the input do ur task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM