大家好,我为我的课程创建了一个对象,并尝试将其输出为BOb,c和1900.543,但该程序的名称和类型为空白,平衡为0。 任何人都可以帮助我,并告诉我我的程序输出不符合预期的问题是什么。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Record{
private:
string newName;
char newType;
double newBalance;
public:
Record(string, char, double);
Record();
string getName();
char getType();
double getBalance();
};
Record::Record(string name, char type, double balance)
{
balance = newBalance;
name = newName;
type = newType;
}
string Record::getName()
{
return newName;
}
char Record::getType()
{
return newType;
}
double Record::getBalance()
{
return newBalance;
}
int main()
{
string name = "Bob";
char type = 'c';
double balance = 1900.543;
Record c1(name, type, balance);
cout << c1.getName() << endl;
cout << c1.getBalance() << endl;
cout << c1.getType() << endl;
return 0;
}
答案 0 :(得分:3)
在发布到论坛之前,请尝试调试。
Record::Record(string name, char type, double balance)
{
balance = newBalance;
name = newName;
type = newType;
}
将此更改为
Record::Record(string name, char type, double balance)
{
newBalance = balance;
newName = name;
newType = type;
}
答案 1 :(得分:2)
之所以发生此错误,是因为编译器无法就此警告您。
为了避免这种情况,您可以使用类似以下的构造函数初始化器列表:
Record::Record(string name, char type, double balance): newBalance(balance), newName(name), newType(type)
{
}
假设您已像在代码中那样反转了成员变量和参数的位置:
Record::Record(string name, char type, double balance): balance(newBalance), name(newName), type(newType)
{
}
编译器会指出此错误:
error: class 'Record' does not have any field named 'balance'
Record::Record(string name, char type, double balance): balance(newBalance), name(newName), type(newType)
^~~~~~~
error: class 'Record' does not have any field named 'name'
Record::Record(string name, char type, double balance): balance(newBalance), name(newName), type(newType)
^~~~
error: class 'Record' does not have any field named 'type'
Record::Record(string name, char type, double balance): balance(newBalance), name(newName), type(newType)