C ++错误地为字符串添加字符串

时间:2012-03-20 03:45:58

标签: c++ string parameters character

我对C ++比较陌生,并且在传递字符串时遇到问题。我有一个类的构造函数,Transaction。“一个构造函数接受一个字符串,一个double作为参数,而另一个只接受一个字符串。

当我试图传递下面的行时,我收到错误,说:

no matching function for call to 'Account::addTransaction(const char [14])'

no matching function for call to 'Account::addTransaction(const char [11], double&)'

我知道没有匹配功能,因为我传递了一个字符串!这就是我传递的内容:

bank.getAccount(index).addTransaction("Close Account");
bank.getAccount(index).addTransaction("Withdrawal", amount_to_withdraw);

我不知道如何更明确地说明第一个参数是一个字符串。任何建议都将不胜感激。

谢谢, 亚当

根据@ g24l的请求更新:

这是交易类:

#ifndef TRANSACTION_H
#define TRANSACTION_H

#include <iostream>
#include <string>
using namespace std;

class Transaction {

private:
    string transType;
    double transAmount;

/*
 public constructors:
 * 1st constructor is the default constructor
 * 2nd constructor is for non-monetary transactions
 * 3rd constructor is for transactions involving money
 */
public:
    Transaction() {
        transType = "";
    }
    Transaction(string tType) {
        transType = tType;
    }

    Transaction(string tType, double tAmount) {
        transType = tType;
        transAmount = tAmount;
    }

    void setTransType(string);
    void setTransAmount(double);

    string getTransType() const;
    double getTransAmount() const;
};
#endif  /* TRANSACTION_H */

在Account类中,它为一组事务使用动态内存分配,我有:

class Account{
private:
    Depositor depositor;
    int accountNum;
    string accountType;
    double accountBalance;
    string accountStatus;
    Transaction *transptr;
    int numTransactions; //number of transactions

public:
    // public member functions prototypes

    // Constructors

    /* Account default constructor:
     * Input:
     *  Depositor() - calls the default depositor constructor
     * Process:
     *  sets object's data members to default values
     * Output:
     *  object's data members are set
     */

    Account()
    {
        //cout << "Account default constructor is running" << endl;
        Depositor();
        accountNum = 0;
        accountType = "";
        accountBalance = 0.0;
        accountStatus = "open";
        transptr = new Transaction[100];
        numTransactions = 0;
    }

我想知道,当我声明事务数组时,它是否使用默认构造函数参数填充所有事务。当我“添加”一个交易时,我真的在写现有的交易。

3 个答案:

答案 0 :(得分:1)

将其包装在std :: string

bank.getAccount(index).addTransaction(std::string("Close Account"));

答案 1 :(得分:1)

bank.getAccount.addTransactionTransaction作为参数。所以传递一个:

bank.getAccount(index).addTransaction(Transaction("Close Account"));
bank.getAccount(index).addTransaction(Transaction("Withdrawal", amount_to_withdraw));

答案 2 :(得分:0)

不,"Close Account" 指向由NUL字符终止的char数组的指针 - 这使得它成为C风格的字符串,但不是 C ++字符串。如果你想强制它成为一个字符串,请明确地创建一个字符串:

bank.getAccount(index).addTransaction(std::string("Close Account"));

(或添加addTransaction的变体,同时接受char *作为第一个参数,但我不会自己提出建议。)