English 中文(简体)
如果基数和产阶级都有相同的成员变量,汇编者将如何确定哪些成员被称作成员?
原标题:If both base and derive class has a same member variable, how compiler resolve which member is to be called?
  • 时间:2012-05-01 11:34:07
  •  标签:
  • c++
Look at this example

class base {
public:
    int m1;
    base() {
        m1 = 5;
    }
};

class der:  public base  {
public:
    int m1;
    der() {
        m1 = 6;
    }
};

int main() {
    der d;
    cout << d.m1;   
    return 0;
}

此处的物体大小为8 byte8, 分配给2 m1(一个用于基类,另一个用于基类)。 解决<代码>d.m1的机制是什么?

最佳回答

<代码>m1 in deriddens the name of base sm1, so any access to m1 through a der/code> 物体请上<代码>der:m1。 查阅<条码>基准:m1,<条码>。 类似:

class der:  public base  {
public:
    int m1;
    der() {
        m1 = 6;
        base::m1=7; // access base object s m1 inside der
    }
};

因此,你可以进入基点:

der d;
d.base; // base object
std::cout << d.base::m1 >> "
"; // access base object s m1 outside of der (if allowed)
问题回答

编辑根据<编码>d的静态类型决定m1。 这意味着,你将取得不同结果。

der d;
cout << d.m1;

以及

der d;
base &b = d;
cout << b.m1;

这是因为在解决<代码>m1时,关于表示类型<编码>>>,成员<代码>der:m1 隐藏在<代码>底:m1上。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签