从基类更改对象的参数!!! [英] change a parameter from a object from base class !!!

查看:47
本文介绍了从基类更改对象的参数!!!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有问题

我有一个基类:



  class 基础
{
public
myClass * a;
虚拟 void 更新(){}

};



和另一个班级:



  class  NewClass: public  Base 
{
public
NewClass();
虚拟 void 更新()
{
a-> val = 200 ;
}
}





现在我这样做:

 myClass * b; 
基础我;
me = NewClass();
me.a = b;
me.Update();





但现在b不要改变。我想要改变b值。我怎么能这样做?

解决方案

我没有尝试过,但我不希望你的代码编译。



您在这里描述了3个类:Base,NewClass和myClass。 Base包含一个指向myClass的指针,该指针在您提供的代码中未定义(错误)。如果你以某种方式忽略了它并以某种方式定义它,在代码的下半部分:



 1 myClass * b; 
2基础我;
3 me = NewClass();
4 me.a = b;
5 me.Update();





第2行和第3行可合并为



 2/3 Base me = NewClass(); 





代表使用一个复制构造函数,构建一个新的''Base''对象,从一个新的''NewClass''临时对象复制元素。此时,me.a未定义(通常是大多数编译器从堆栈中丢弃)。第4行应该指定me.a值b(在堆栈上),第5行将改变b-> val。



假设:

(1)我们在这里谈论C ++。例如,Java做了不同的事情。

(2)这段代码段在相关类的外部。

(3)myClass包含名为''val''的东西(这是很好的POD而不是属性或其他时髦的东西。



你没有提供类myClass的代码,这可能会改变以上所有内容。


很抱歉,但是您对指针的使用感到困惑



 a =  200 ;  //  错误 





你可能想做什么



 * a =  200 ; 


Hi I have a problem
I have a base class :

class Base
{
public:
    myClass* a;
    virtual void Update(){}

};


and another class :

class NewClass:public Base
{
public:
    NewClass();
    virtual void Update()
    {
        a->val=200;
    }
}



now I do this :

myClass* b;
Base me;
me=NewClass();
me.a=b;
me.Update();



but now b dont change. I want change b value. how can I do this like this ?

解决方案

I haven''t tried it but I wouldn''t expect your code to compile.

You are describing 3 classes here: Base, NewClass and myClass. Base includes a pointer to myClass, which in your code as provided, is not defined (error). If you somehow overlook this and define it somehow, in the lower section of code:

1    myClass* b;
2    Base me;
3    me=NewClass();
4    me.a=b;
5    me.Update();



Lines 2 and 3 could be combined as

2/3    Base me=NewClass();



which represents use of a copy constructor, building a new ''Base'' object, copying elements from a new ''NewClass'' temporary object. At this point, me.a is undefined (usually trash from the stack with most compilers). Line 4 should assign me.a the value of b (on the stack) and line 5 will change b->val.

Assumptions:
(1) We are talking C++ here. Java for example does something different.
(2) This code segment is external to the classes in question.
(3) myClass contains something named ''val'' (which is well formed POD and not a property or something else funky).

You didn''t provide the code for class myClass, which could change all of the above.


I am sorry, but you have confused the usage of pointers

a=200; // is wrong



you probably want to do

*a = 200;


这篇关于从基类更改对象的参数!!!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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