You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何已在bankdeposit类中声明show成员仍报未声明错误?

问题原因与解决方法

你遇到的错误核心是**show函数没有在bankdeposit类的公共成员区域正确声明**——你把void show();写在了第二个构造函数的函数体内部,这只是一个局部的函数声明,不属于类的成员,编译器自然会认为类里没有show这个成员。

修复步骤

  • 把void show();的声明从构造函数内部移到bankdeposit类的public块中,和其他构造函数声明放在一起。
  • 确保类外的show函数实现(void bankdeposit::show(){...})和类内的声明匹配。

修正后的完整代码

#include <iostream>
    
using namespace std;
    
class bankdeposit
{
    int principal, years;
    float interest, returnvalue;
    
public:
    bankdeposit(){};
    bankdeposit(int p, int y, float r); // can be 2.00
    bankdeposit(int p, int y, int r);   // can be 2.
    void show(); // 将show的声明放在类的public区域
};
    
bankdeposit::bankdeposit(int p, int y, float r)
{
    principal = p;
    years = y;
    interest = r;
    returnvalue = principal;
    
    for (int i = 0; i < y; i++)
    {
        returnvalue = returnvalue * (1 + r);
    }
};
    
bankdeposit::bankdeposit(int p, int y, int r)
{
    principal = p;
    years = y;
    interest = float(r) / 100; 
    returnvalue = principal;
    
    for (int i = 0; i < y; i++)
    {
        // 这里要注意:应该用转换后的interest变量,而不是原参数r,否则计算结果错误
        returnvalue = returnvalue * (1 + interest);
    }
};
    
void bankdeposit::show(){
    // 可以在这里添加输出逻辑,比如展示存款信息
    cout << "本金: " << principal << endl;
    cout << "存期: " << years << "年" << endl;
    cout << "到期本息: " << returnvalue << endl;
}
    
int main()
{
    // 测试示例
    bankdeposit bd(1000, 3, 5);
    bd.show();
    return 0;
}

额外提醒:第二个构造函数的循环计算原本存在逻辑错误,原代码用了未转换的整数参数r参与计算,会导致本息结果异常,上面的修正代码已经改成使用转换后的interest变量。

内容的提问来源于stack exchange,提问作者Yash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 11:45:31