类中的成员函数

时间:2016-10-14 17:12:52

标签: c++

类中的成员函数是否可以具有另一个类的返回类型?

    public void updateTrophyView(ScoreHolder holder, int newScore, int position, ViewGroup parent) {
    ListView parentListView = (ListView) parent;
    Log.wtf(TAG, "updating Trophy View?");
    if (highestScore != 0) {
        Log.wtf(TAG, "hidden old view?");
        //highestScorerTrophyView.setVisibility(View.INVISIBLE);

        //View retiredWinner = parentListView.getChildAt(oldPosition - parentListView.getFirstVisiblePosition());
        //retiredWinner.findViewById(R.id.trophyView).setVisibility(View.INVISIBLE)
    }
    Log.i(TAG, "toggling visibility?");
    highestScore = newScore;
    ((ImageView) parentListView.getChildAt(position - parentListView.getFirstVisiblePosition())
            .findViewById(R.id.trophyView)).setImageResource(R.drawable.ic_trophy);//.setVisibility(View.VISIBLE);
    //newLeader.setImageResource(R.drawable.ic_trophy);
    //newLeader.setVisibility(View.VISIBLE);
    //TODO need to find a reference to entire list

    /* THIS IS NOT CHANGING THE UNDERLYING DATA SET, JUST THE VIEWS,
    *  so when goes of screen adapter erases views, forgets changes.
    highestScore = newScore;
    holder.trophyImageView.setVisibility(View.VISIBLE);
    highestScorerTrophyView = holder.trophyImageView; */
    // need to make sure the listView the adapter is connected to is updated.
    notifyDataSetChanged();
}

这是允许的吗?

3 个答案:

答案 0 :(得分:1)

是的,您可以返回任何有效类型,如果该类型允许,则对于成员函数可以返回的常规函数​​没有其他限制。

虽然在您的代码示例中func()无法返回类型B的对象,因为它尚未定义。您需要在class B之前移动class A定义或使用前向声明,然后只在那里声明(不定义)A::func,然后您可以在{{1}之后定义(实现)它定义:

class B

有关前向声明的其他详细信息,请访问here

答案 1 :(得分:0)

是的,只要编译器在您声明B之前知道func。通过在class B {};之前写class A,将B的定义移到class B;之上,或转发声明class A

答案 2 :(得分:0)

是的,只要您按顺序放置类,就允许这样做。目前,您的示例不起作用。它是:

class A
{
    int a,b;
public:
    B func(int x); // func returns type B which is another class
};

class B
{
};

您需要将A类放在A之前,如下所示:

class B
{
};
class A
{
    int a,b;
public:
    B func(int x); // func returns type B which is another class
};

Or Forward声明:

class B; //Forward Declaration.
class A
{
    int a,b;
public:
    B func(int x); // func returns type B which is another class
};

class B
{
};

否则,您的代码应该有效。