C ++为什么我的构造函数不起作用?

时间:2014-04-21 06:35:50

标签: class constructor

我正在使用visual c ++ 2010,而我遇到了类构造函数问题。我写的完全像我的导师所描述的那样,我似乎无法弄清楚为什么它不会编译。

#include <iostream>;
using namespace std;

class Account
{
public:
Insert other functions here...
Account(float b)
{
    Balance = b;
}

private:
float &Balance;
}

Int main()
{   
float withdraw,deposit;
Account myAccount(100.00);

cout << "Enter the amount you would like to withdraw:" << endl;
cin >> withdraw;
MyAccount.debt(withdraw);
cout << "Your balance is now "<< endl;
MyAccount.showAccountInfo();
cout << endl;
cout << "Enter the amount you would like to deposit: " << endl;
cin >> deposit;
myAccount.credit(deposit);
cout << "Your balance now is " << endl;
MyAccount.showAccountInfo();
cout << endl;

return 0;

}

2 个答案:

答案 0 :(得分:2)

您可能已将成员Balance声明为引用,并且您正在使用常量(即100.00)调用构造函数,您必须将变量名称传递给构造函数或声明不带引用运算符的成员。

答案 1 :(得分:0)

如果您需要在过程的不同部分进行平衡,可以使用动态内存进行尝试。

例如:

class Account
{
 public:
 Insert other functions here...
 Account(float* b)
 {
  Balance = b;
 }

 private:
 float* Balance;
}

Int main()
{   
 float withdraw,deposit;
 Account myAccount(new float(100.0));

 cout << "Enter the amount you would like to withdraw:" << endl;
 cin >> withdraw;
 MyAccount.debt(withdraw);
 cout << "Your balance is now "<< endl;
 MyAccount.showAccountInfo();
 cout << endl;
 cout << "Enter the amount you would like to deposit: " << endl;
 cin >> deposit;
 myAccount.credit(deposit);
 cout << "Your balance now is " << endl;
 MyAccount.showAccountInfo();
 cout << endl;

 return 0;

在更新余额方法中,您应该取消引用指针:

例如......

 void debt(float withdraw){
     *balance -= withdraw;
 }

谢谢,问候。