const char数组多初始化c ++

时间:2016-07-19 06:41:24

标签: c++ inheritance char const

我在public class AccountDetailsActivity extends SherlockActivity implements AsyncResponse { protected Button submitBtn; String uuid = ""; String accnum=""; String ib=""; AccountDetailsListAdapter adapter; ArrayList<Object> arr = new ArrayList<Object>(); public String endTime = ""; public String startTime = ""; public String maximumAccountBalance = ""; public String minimumAccountBalance = ""; public boolean accountCredited = false; public boolean accountDebited = false; public boolean incomingTransfer = false; public boolean salaryCredited = false; public boolean accountBalance = false; public boolean failedStandingOrders = false; public boolean creditCardPayment = false; public boolean accountOverdrawn = false; private class AccountItemListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(arr.get(position) instanceof Account) { Intent i = new Intent(getApplicationContext(), TransactionHistoryDetailsActivity.class); Account accountItem = (Account) arr.get(position); i.putExtra("description", accountItem.getAccountNumber()); i.putExtra("runningBalance", accountItem.getBalance()); i.putExtra("creditAmount", accountItem.getCurrency2()); i.putExtra("reference", accountItem.getReference()); i.putExtra("postingDate", accountItem.getType()); i.putExtra("valueDate", accountItem.getLedgerBalance()); i.putExtra("debitAmount", accountItem.getDebitAmount()); startActivity(i);}}} @Override public void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); setContentView(R.layout.details_subpage_list); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); if (!Common.getItemSelection(AccountDetailsActivity.this).equals( "osmething")) { SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(AccountDetailsActivity.this); String theme = settings.getString("theme", ""); if(theme != null && theme.trim().toLowerCase().equals("premium")) { getSupportActionBar().setIcon(R.drawable.ic_launcherg); } else if(theme != null && theme.trim().toLowerCase().equals("private")) { getSupportActionBar().setIcon(R.drawable.ic_private); } else { getSupportActionBar().setIcon(R.drawable.ic_launcher); } } Bundle extras = getIntent().getExtras(); String accountNumber = ""; String iban = ""; String balance = ""; String type = ""; String currency = ""; String overdraftLimit = ""; String nickName = ""; String ledgerBalance = ""; HeaderItem x11 = new HeaderItem(); x11.setText(getResources().getString(R.string.accountDetails).toUpperCase()); arr.add(x11); if (extras != null) { uuid = extras.getString("uuid"); accountNumber = extras.getString("accountNumber"); accnum = accountNumber; iban = extras.getString("iban"); ib = iban; balance = extras.getString("balance"); type = extras.getString("type"); currency = extras.getString("currency"); overdraftLimit = extras.getString("overdraftLimit"); nickName = extras.getString("nickName"); ledgerBalance = extras.getString("ledgerBalance"); getSupportActionBar().setTitle(nickName); arr.add(accountNumber); arr.add(type); arr.add(iban); arr.add(currency); arr.add(ledgerBalance);// ledger balance arr.add(overdraftLimit); arr.add(balance); accountCredited = extras.getBoolean("accountCredited"); accountBalance = extras.getBoolean("accountBalance"); failedStandingOrders = extras.getBoolean("failedStandingOrders"); accountOverdrawn = extras.getBoolean("accountOverdrawn"); incomingTransfer = extras.getBoolean("incomingTransfer"); salaryCredited = extras.getBoolean("salaryCredited"); creditCardPayment = extras.getBoolean("creditCardPayment"); accountDebited = extras.getBoolean("accountDebited"); maximumAccountBalance = extras.getString("maximumAccountBalance"); minimumAccountBalance = extras.getString("minimumAccountBalance"); endTime = extras.getString("endTime"); startTime = extras.getString("startTime"); } ListView accountDetailsList = (ListView) findViewById(R.id.list_accounts_details); adapter = new AccountDetailsListAdapter( getApplicationContext(), arr); accountDetailsList.setAdapter(adapter); accountDetailsList.setOnItemClickListener(new AccountItemListener()); processFinish(//some json here); } catch (Exception e) { } } @Override public void processFinish(StringBuilder output) { try { HeaderItem x11 = new HeaderItem(); x11.setText(getResources().getString(R.string.transactionHistory1).toUpperCase()); arr.add(x11); JSONObject jsonObj = new JSONObject(output.toString()); String status = jsonObj.getString("status"); String status1 = jsonObj.optString("message", ""); if (status != null && status.trim().equals("2006")) { } else if (status.equals("1000")) { JSONObject data = jsonObj.getJSONObject("data"); JSONArray contacts = data.getJSONArray("transactions"); for (int i = 0; i < contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String accountNumbr = c.optString("description", ""); String availableBalance = c.optString("balance", ""); String type = c.optString("postingDate", ""); String iban = c.optString("creditAmount", ""); String valueDate = c.optString("valueDate", ""); String reference = c.optString("reference", ""); String debitAmount = c.optString("debitAmount", ""); Account acc = new Account(); acc.setAccountNumber(accountNumbr); acc.setType(type); acc.setCurrency(""); acc.setBalance(availableBalance); acc.setCurrency2(iban); acc.setLedgerBalance(valueDate); acc.setReference(reference); acc.setHistoryAccount("1"); acc.setDebitAmount(debitAmount); acc.setPath(uuid); arr.add(acc); } } adapter.notifyDataSetChanged(); } catch(Exception e) { } }} 课程中有一个const char数组。

Base

我创建了一个子static const char *_myArray[10]; 类的CPP文件,可以使用以下语法初始化Child1

_myArray[10]

我创建了另一个子名const char *Base::_myArray[10] = {"red", "green", "blue"}; ,我需要使用Child2值初始化此数组。

我在{"pink", "yellow", "brown"}中尝试过类似的方法,但是,它无法使用这种方式初始化数组。它给出了编译错误,即多个初始化存在问题。

我在我的Base类实例中使用此数组(从派生类转换),并且应该从派生类填充数据(因为数据可能因子节点而异)。

解决此问题的正确方法是什么? 非常感谢您的支持。

提前谢谢!

4 个答案:

答案 0 :(得分:1)

静态变量可以初始化一次。初始化静态成员时,告诉编译器这个静态变量在哪个编译单元中。您已经在Child1中初始化了该变量,您无法在Child2中执行此操作。

答案 1 :(得分:0)

您的问题是static关键字。这意味着此类的所有实例共享一个数组(如果声明为public,则该数组甚至可以在没有任何实例的情况下访问)。因此,您使用{"red", "green", "blue"}初始化数组,之后,由于数组为const,因此无法再进行更改。然后,您尝试使用{"pink", "yellow", "brown"}再次初始化它,这将导致错误。

为什么这个数组必须是静态的?删除静态并在构造函数的初始化列表中进行初始化。

以下是此方法的正确语法:

Base::Base() : _myArray{"red", "green", "blue"} 
{
    // Constructor here
}

我还注意到的问题是,你将这个一维数组视为二维的。数组的每个单元格只能存储一个字符,而不能存储C字符串。您可以通过使用二维数组或使用std::strings数组来解决这个问题。

答案 2 :(得分:0)

有一些方法可以解决这个问题: 一种方法是每次在类中显式编写静态成员:

class Base {/*...*/};

class InheritedFirst : public Base
{
    static constexpr const char* _myArray[10] = {"First"};
};

class InheritedSecond : public Base
{
    static constexpr const char* _myArray[10] = {"Second"};
};

另一个是从模板类中删除当前类作为模板参数:

class Base {/*...*/};

template<typename T>
class GimmeArray
{
    static const char* _myArray[10];
};

class InheritedThird : public Base, public GimmeArray<InheritedThird>
{/*...*/};

class InheritedFourth : public Base, public GimmeArray<InheritedFourth>
{/*...*/};

template<typename T>
const char* GimmeArray<T>::_myArray[10] = {"Not specialized"};
template<>
const char* GimmeArray<InheritedThird>::_myArray[10] = {"Third"};
template<>
const char* GimmeArray<InheritedFourth>::_myArray[10] = {"Fourth"};

答案 3 :(得分:0)

目标:

提供一个单词数组,为每个派生类存储一次。同一类的所有实例应共享相同的单词数组。

对共享数组的访问应该是多态的,这样观察者可以在不知道对象的确切类型的情况下访问数组。

在这种情况下,我会在基类上有一个非多态的接口函数,这会推迟到多态实现。

实现将在每个派生类中定义一次,并且应该提供对静态const数组的引用。

作为静态const,c ++将保证它是在第一次使用时创建的。 c ++ 11将保证构造是原子的。

类似的东西:

#include <array>
#include <iostream>
#include <memory>

using words_array = std::array<const char*, 3>;

struct has_words_base
{
public:
    const words_array& get_words() const
    {
        return get_words_impl();
    }

private:
    virtual const words_array& get_words_impl() const
    {
        static const words_array _ { "grey", "black", "brown" };
        return _;
    }

};

struct blue_words : has_words_base
{
private:
    virtual const words_array& get_words_impl() const override
    {
        static const words_array _ { "blue", "cyan", "indigo" };
        return _;
    }

};

struct red_words : has_words_base
{
private:
    virtual const words_array& get_words_impl() const override
    {
        static const words_array _ { "red", "vermillion", "scarlet" };
        return _;
    }
};


void test(const has_words_base& ob)
{
    auto sep = "";
    for (auto&& w : ob.get_words()) {
        std::cout << sep << w;
        sep = ", ";
    }
    std::cout << std::endl;

}

int main()
{
    test(*std::make_unique<has_words_base>());
    test(*std::make_unique<blue_words>());
    test(*std::make_unique<red_words>());

}

预期产出:

grey, black, brown
blue, cyan, indigo
red, vermillion, scarlet