gpt4 book ai didi

c++ - 当我用 case 语句调用自定义对象时,为什么不显示它?

转载 作者:行者123 更新时间:2023-11-28 06:07:28 24 4
gpt4 key购买 nike

我只是想知道为什么当我在其上调用 case(main 中的 switch 语句)时,这个自定义 Account 对象没有显示在我的控制台上?我不会让任何人厌烦大部分代码,但这是我的 .cpp 文件中 Account 类的重载方法:

std::ostream& operator<<(std::ostream& out,const Account& acc) {
out << acc.name << '\n';
out << acc.accountBalance;
return out;
}

我对 Account 参数是否应该是常量感到有点困惑,因为我将根据用户输入更改其状态。我取出了 const 关键字但没有运气。输出类似于这样的 00AA87081。

谢谢!

编辑:

好的,抱歉,这是 main 中的 switch 语句:

switch (choice) {
case 1:
std::cout << "***User registration***" << std::endl;
std::cout << "Please enter your name." << std::endl;
std::cin >> name;
a->setName(name);
break;

case 2:
std::cout << "How much credit do you want to deposit?" << std::endl;
std::cin >> input;
a->deposit(input);
std::cout << "Your account balance is now " << a->getAccountBalance() << std::endl;
break;

case 3:
std::cout << "How many black and white pages do you want to print? - 1 credit per page" << std::endl;
std::cin >> bPages;
a->printBW(bPages);
break;

case 4:
std::cout << "How many colour pages do you want to print? - 2.5 credits per page" << std::endl;
std::cin >> cPages;
a->printC(cPages);
break;

case 5:
std::cout << "Please enter your promotional code." << std::endl;
std::cin >> code;
a->promo(code);
break;

case 6:
std::cout << a << std::endl;
break;

case 7:
std::cout << "Thank you" << std::endl;
exit(0);
break;

default:
std::cout << "Please enter a valid option." << std::endl;
}

} while (choice !=7);

我已经在上面创建了对象,即使我在 switch 语句之外调用 std::cout << a ,它也做同样的事情。

最佳答案

正如我和许多其他人猜测的那样,您正在打印一个指针,这意味着输出将是指针的内容(即它指向的地址)。

要打印对象,您需要用一元 * 取消引用指针运算符(operator):

std::cout << *a << '\n';
// ^
// |
// Notice asterisk here

您可以选择更改 operator<<函数获取类的指针而不是引用(或添加函数的新重载)。

关于c++ - 当我用 case 语句调用自定义对象时,为什么不显示它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32111138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com