关于继承的问题 [英] question about inheritance

查看:80
本文介绍了关于继承的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hi world

我有一个问题。请帮帮我

是否可以将一个对象从父类转换为一个对象到派生类?

i认为这是不可能的,因为派生类有属性和方法可能基类没有它们,但我在visual studio中编写下面的代码并显示未知值。

hi world
i have a question . please help me
is it possible to cast an object from parent class to an object to derived class??
i think it is not possible because derived class have attributes and methodes that may base class doesn't have them but i write the below code in visual studio and it show the unknown value.

class A
{
public:
	string x;
	A():x("kdf"){}
};
class B:public A
{
public:
	B(int i):y(i){}
	int y;
};
int _tmain(int argc, _TCHAR* argv[])
{
	A a;
	cout <<((B&)a).y;
	return 0;
}



但我写的时候


but when i write

class A
{
public:
	string x;
	A():x("kdf"){}
};
class B:public A
{
public:
	B(int i):y(i){}
	int y;
};
int _tmain(int argc, _TCHAR* argv[])
{
	A a;
	cout <<((B)a).y;
	return 0;
}



我有一个错误,但我不知道为什么?

请说明我为什么要放&在行中


i have an error but i don't khow why?
please say me why i should put & in the line

cout <<((B)a).y;



以及为什么我们可以做这个演员?

非常感谢


and why we can do this cast?
thank you very much

推荐答案

你可以做演员,因为 C -like cast运算符就像一个非常大的锤子,编译器知道如何通过引用进行转换(这意味着:解释一个对象的地址,就好像它是一个具有不同类型的对象)。 />
另一方面,你得到错误(在第二种情况下),因为编译器不知道如何转换 A 类型的对象到 B 类型的对象。

底线是:使用 C - 只有当你非常了解自己在做什么时才喜欢施法操作员。
You can do the cast because the C-like cast operator is just like a very big hammer and the compiler knows how to cast by reference (that means: interpret the address of an object like if it was the one of an object having different type).
On the other hand, you get the error (in the second scenario), because the compiler doesn't know how to convert an object of type A to an object of type B.
The bottom line is: use the C-like cast operator only if you know very well what you are doing.


虽然CPallini已经非常恰当地将C风格的演员阵容与一把非常大的锤子进行比较,但我想添加一个不同的,但也非常贴合图片:



你实际做的是t ake bike(A),在它上面放了一个大标签,上面写着'这是一辆坦克!'(这是一辆B),然后你试图越过刚过的公共汽车。现在猜猜谁会崩溃!



只是因为你告诉编译器你的'自行车'是'坦克',并不是这样。它就是这样的:类型转换是告诉编译器的一种方式:无论你在想什么,我都知道更好;这是一种不同的类型!。我看到很多程序员坐在破旧的自行车上这样做...... X |
While CPallini already quite fittingly compared the C-style cast to a very big hammer, I'd like to add a different, but also very fitting comparison to the picture:

What you have actually done is take bike (an A), put a big label on it saying 'This is a tank!' (this is a B), and then you tried to run over the bus that was just passing by. Now guess who's gonna crash!

Just because you tell the compiler that your 'bike' is a 'tank', doesn't make it so. And it's really just that: a typecast is a way to tell the compiler: "Whatever you're thinking, I know better; this is a different type!". I've seen many programmers doing that while sitting on shabby bikes... X|


这篇关于关于继承的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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