变体返回类型Upcasting覆盖c ++

时间:2015-08-21 12:25:51

标签: c++ polymorphism override upcasting

我在以下示例中遇到clone()方法的问题。我预计sizeof(*((*ptr1).clone()))b1相同,sizeof(*(ptr2.clone()))的大小为c1,但事实并非如此。他们是sizeof(a1)。我错过了什么?

这是代码。

class A
{int a;
public:
    virtual A * clone() {return this;}
};

class B : public A
{int b,c;
public:
    B * clone() {return this;}
};

class C : public A
{int b,c,d;
public:
    C * clone() {return this;}
};

int main()
{
    A a1;
    B b1;
    C c1;
    A * ptr1 = &b1;
    A & ptr2 = c1;
    std::cout << "sizeof(a1) = " << sizeof(a1) << '\n';
    std::cout << "sizeof(b1) = " << sizeof(b1) << '\n';
    std::cout << "sizeof(*(b1.clone())) = " << sizeof(*(b1.clone())) << '\n';
    std::cout << "sizeof(c1) = " << sizeof(c1) << '\n';
    std::cout << "sizeof(*((*ptr1).clone()))" << sizeof(*((*ptr1).clone())) << '\n';
    std::cout << "sizeof(*(ptr2.clone()))" << sizeof(*(ptr2.clone())) << '\n';
    return 0;
}

2 个答案:

答案 0 :(得分:2)

sizeof(*((*ptr1).clone()))是编译时间值,并且不执行表达式。

所以我们sizeof(*((*std::declval<A*>()).clone())) sizeof(A) A::clone()(我们使用A*返回public View view_title, view_text public ViewHolder(View v) { super(v); ... view_title = v.findViewById(R.id.title); view_text = v.findViewById(R.id.text); title = (TextView) v.findViewById(R.id.title); text = (TextView) v.findViewById(R.id.text); ... } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { holder.title.setText(utilsM.getTitleByPos("tasks", position)); holder.text.setText(utilsM.getNoticeByPos("tasks", position)); if ( ( holder.title.getText().length() > 0) && (holder.text.getText().length() == 0) ) { holder.view_title.setVisibility(View.VISIBLE); holder.view_text.setVisibility(View.INVISIBLE); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.view_title.getLayoutParams(); params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE); holder.view_title.setLayoutParams(params); debug("title: " + holder.title.getText()); debug("text: " + holder.text.getText()); } else if ( ( holder.text.getText().length() > 0) && (holder.title.getText().length() == 0) ) { holder.view_title.setVisibility(View.INVISIBLE); holder.view_text.setVisibility(View.VISIBLE); RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) holder.view_text.getLayoutParams(); params2.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE); holder.view_text.setLayoutParams(params2); } else { holder.view_title.setVisibility(View.VISIBLE); holder.view_text.setVisibility(View.VISIBLE); } )。

答案 1 :(得分:1)

sizeof仅考虑其参数的静态类型,而不考虑动态类型。因此sizeof的参数可以是未评估的操作数,sizeof的结果不依赖于任何运行时信息(例如动态类型信息所需的vtable)。因此sizeof的结果始终是编译时常量表达式,适合用于例如作为模板参数。

参见C ++ 11:§5.3.3[expr.sizeof] / 2。