如何解决这些 cpp 错误?

如何解决如何解决这些 cpp 错误?

使用 VISUAL STUDIO 2019

我收到的错误是:

E0065 - 第 104 行

E0112 - 第 133 行

C2601 - 第 134 行

C2601 - 第 146 行

我尝试过重新排列代码段、删除或更改其他代码段,并且已经用尽了我能想到的选项。不太确定出了什么问题,任何帮助表示赞赏。如果需要,我也可以提供我遵循的方向的屏幕截图。

// bring in libraries

#include <iostream>
#include <conio.h>
#include <string>
#include <fstream> // read/write to files
#include <ctime> // time(0)
#include <iomanip> // setprecision( )
using namespace std;
    
    // prototypes
    void deposit(double* ptrBalance);
    void withdrawal(double* ptrBalance,float dailyLimit); // overloaded method this version does not take withdrawal amount
    void withdrawal(double* ptrBalance,float dailyLimit,float amount); // overloaded method that takes withdrawal amount

/// Entry point to the application
int main()
{

    // Create constant variables
    const int EXIT_VALUE = 5;
    const float DAILY_LIMIT = 400.0f;
    const string FILENAME = "Account.txt";


    // create loop variable BEFORE the loop
    short choice = 0;

    // Create balance variable
    double balance = 0.0;

    // Look for the starting balance; otherwise generate a random starting balance
    ifstream iFile(FILENAME.c_str());
    if(iFile.is_open())
    {
        // Did the file open? If so,read the balance.
        iFile >> balance;
        iFile.close();
    }
    else
    {

        // If the file did not open or does not exist,create a random number for the starting balance
        srand(time(0));
        const int MIN = 1000;
        const int MAX = 10000;
        balance = rand() % (MAX - MIN + 1) + MIN;
    }

    std::cout << fixed << setprecision(2) << "Starting Balance: $" << balance << endl;

    // Let's create a pointer and set it to the balance variable location
    double* ptrBalance = &balance; // & means "address of"

        // start the application loop
    do
    {

        // show the menu
        system("cls"); // clears the console screen -- for MAC,use system("clear");
        std::cout << "Menu\n" << endl;
        std::cout << "1) Deposit " << endl;
        std::cout << "2) Withdrawal" << endl;
        std::cout << "3) Check Balance" << endl;
        std::cout << "4) Quick $40" << endl;
        std::cout << "5) Exit" << endl;

        // get user input
        std::cout << "\nEnter your choice: ";
        cin >> choice;

        // run code based on user input
        switch (choice)
        {
        case 1:
            deposit(ptrBalance); // Passing a pointer so only 4 bytes have to cross the system bus
            break;
        case 2:
            withdrawal(ptrBalance,DAILY_LIMIT);
            break;
        case 3:
            std::cout << "Showing current balance..." << endl;
            break;
        case 4:
            std::cout << "Getting quick $40..." << endl;
            break;
        case 5:
            std::cout << "\nGoodbye" << endl;
            break;
        default:
            std::cout << "\nError. Please select from the menu." << endl;
            break;
        }


        /// Make a deposit
        void deposit(double* ptrBalance)
        {
            // get deposit and validate it
            float deposit = 0.0f;

            do
            {
                std::cout << "\nEnter deposit amount";
                cin >> deposit;

                if (cin.fail()) // did they give us a character instead of a number?
                {
                    cin.clear(); // clears fail state
                    cin.ignore(INT16_MAX,'\n'); // clears keyboard buffer
                    std::cout << "\nError. Please input numbers only.\n" << endl;
                    deposit = -1; // set deposit to a "bad" number
                    continue; // restart the loop
                }
                else if (deposit < 0.0f) // check for negative number
                    std::cout << "\nError. Invalid deposit amount.\n" << endl;
            } while (deposit < 0.0f);

            // How do we get the double value located at the pointer?
            // Dereference it using an asterisk
            *ptrBalance += deposit; // same as: *ptrBalance = ptrBalance + deposit;

            std::cout << fixed << setprecision(2) << "\nCurrent ptrBalance: $" << *ptrBalance << endl; // notice asterisk
        }

        /// Make a withdrawal
        void withdrawal(double* ptrBalance,float dailyLimit)
        {
            // get the withdrawal (you should validate this input
            float amount = 0.0f;
            std::cout << "\nEnter withdrawal amount: ";
            cin >> amount;

            // call the overloaded method version that takes the balance,dailyLimit,and withdrawal amount
            withdrawal(ptrBalance,amount);
        }

        /// Make a withdrawal - this overload accepts balance,and withdrawal amount
        void withdrawal(double* ptrBalance,float amount)
        {
            // take money away from account and show the balance
            if (amount > dailyLimit)
            {
                cout << "\nError. Amount exceeds daily limit." << endl;
            }
            else if (amount > * ptrBalance) // notice the asterisk to dereference the pointer!
            {
                cout << "\nError. Insufficient funds." << endl;
            }
            else
            {
                *ptrBalance -= amount; // same as: *ptrBalance = *ptrBalance - amount;
                cout << "\nHere is your cash: $" << amount << endl;
            }
        }
            cout << fixed << setprecision(2) << "\nCurrent ptrBalance: $" << *ptrBalance << endl;
        

        // pause
        std::cout << "\nPress any key to continue...";
        _getch();
    
    while (choice != EXIT_VALUE);
    return 0;
    // now that the application has ended,write the new balance to the file
    ofstream oFile(FILENAME.c_str());
    oFile << balance << endl;
    oFile.close();

    return 0;
    
    // pause before we clear the screen
    std::cout << "n\Press any key to continue...";
        _getch();

}

解决方法

C++ 不允许您在另一个函数中定义一个函数。这样做的唯一方法是使用 lambdas。所以在定义一个函数时,不要在另一个函数内部定义它,而是在其他地方定义它。还有一些其他错误(和警告),我已经更正并注释掉了。

// bring in libraries

#include <iostream>
#include <conio.h>
#include <string>
#include <fstream> // read/write to files
#include <ctime> // time(0)
#include <iomanip> // setprecision( )
using namespace std;

// prototypes   <-- You dont need these.
//void deposit(double* ptrBalance);
//void withdrawal(double* ptrBalance,float dailyLimit); // overloaded method this version does not take withdrawal amount
//void withdrawal(double* ptrBalance,float dailyLimit,float amount); // overloaded method that takes withdrawal amount

/// Make a deposit
void deposit(double* ptrBalance)
{
    // get deposit and validate it
    float deposit = 0.0f;

    do
    {
        std::cout << "\nEnter deposit amount";
        cin >> deposit;

        if (cin.fail()) // did they give us a character instead of a number?
        {
            cin.clear(); // clears fail state
            cin.ignore(INT16_MAX,'\n'); // clears keyboard buffer
            std::cout << "\nError. Please input numbers only.\n" << endl;
            deposit = -1; // set deposit to a "bad" number
            continue; // restart the loop
        }
        else if (deposit < 0.0f) // check for negative number
            std::cout << "\nError. Invalid deposit amount.\n" << endl;
    } while (deposit < 0.0f);

    // How do we get the double value located at the pointer?
    // Dereference it using an asterisk
    *ptrBalance += deposit; // same as: *ptrBalance = ptrBalance + deposit;

    std::cout << fixed << setprecision(2) << "\nCurrent ptrBalance: $" << *ptrBalance << endl; // notice asterisk
}

/// Make a withdrawal - this overload accepts balance,dailyLimit,and withdrawal amount
void withdrawal(double* ptrBalance,float amount) // Place this before the other overload as its used by the other one.
{
    // take money away from account and show the balance
    if (amount > dailyLimit)
    {
        cout << "\nError. Amount exceeds daily limit." << endl;
    }
    else if (amount > *ptrBalance) // notice the asterisk to dereference the pointer!
    {
        cout << "\nError. Insufficient funds." << endl;
    }
    else
    {
        *ptrBalance -= amount; // same as: *ptrBalance = *ptrBalance - amount;
        cout << "\nHere is your cash: $" << amount << endl;
    }
}

/// Make a withdrawal
void withdrawal(double* ptrBalance,float dailyLimit)
{
    // get the withdrawal (you should validate this input
    float amount = 0.0f;
    std::cout << "\nEnter withdrawal amount: ";
    cin >> amount;

    // call the overloaded method version that takes the balance,and withdrawal amount
    withdrawal(ptrBalance,amount);
}

/// Entry point to the application
int main()
{

    // Create constant variables
    const int EXIT_VALUE = 5;
    const float DAILY_LIMIT = 400.0f;
    const string FILENAME = "Account.txt";


    // create loop variable BEFORE the loop
    short choice = 0;

    // Create balance variable
    double balance = 0.0;

    // Look for the starting balance; otherwise generate a random starting balance
    ifstream iFile(FILENAME.c_str());
    if (iFile.is_open())
    {
        // Did the file open? If so,read the balance.
        iFile >> balance;
        iFile.close();
    }
    else
    {

        // If the file did not open or does not exist,create a random number for the starting balance
        srand(static_cast<unsigned int>(time(0)));  // Cast it to unsigned int.
        const int MIN = 1000;
        const int MAX = 10000;
        balance = static_cast<double>(rand() % (MAX - MIN + 1) + MIN);
    }

    std::cout << fixed << setprecision(2) << "Starting Balance: $" << balance << endl;

    // Let's create a pointer and set it to the balance variable location
    double* ptrBalance = &balance; // & means "address of"

        // start the application loop
    do
    {

        // show the menu
        system("cls"); // clears the console screen -- for MAC,use system("clear");
        std::cout << "Menu\n" << endl;
        std::cout << "1) Deposit " << endl;
        std::cout << "2) Withdrawal" << endl;
        std::cout << "3) Check Balance" << endl;
        std::cout << "4) Quick $40" << endl;
        std::cout << "5) Exit" << endl;

        // get user input
        std::cout << "\nEnter your choice: ";
        cin >> choice;

        // run code based on user input
        switch (choice)
        {
        case 1:
            deposit(ptrBalance); // Passing a pointer so only 4 bytes have to cross the system bus
            break;
        case 2:
            withdrawal(ptrBalance,DAILY_LIMIT);
            break;
        case 3:
            std::cout << "Showing current balance..." << endl;
            break;
        case 4:
            std::cout << "Getting quick $40..." << endl;
            break;
        case 5:
            std::cout << "\nGoodbye" << endl;
            break;
        default:
            std::cout << "\nError. Please select from the menu." << endl;
            break;
        }


        cout << fixed << setprecision(2) << "\nCurrent ptrBalance: $" << *ptrBalance << endl;


        // pause
        std::cout << "\nPress any key to continue...";
        _getch();

    } while (choice != EXIT_VALUE);

    //return 0; <-- You cannot have multiple returns.

    // now that the application has ended,write the new balance to the file
    ofstream oFile(FILENAME.c_str());
    oFile << balance << endl;
    oFile.close();

    // pause before we clear the screen
    std::cout << "\nPress any key to continue...";  // It should be \n,not n\
    _getch();

    return 0;   // Place the return at the end.
}
,

在您的代码版本中,您已经在 main() 中定义了函数。在 C++ 中,不允许这样做,即在另一个函数中定义一个函数。你不能在另一个函数的范围内实现一个函数。

由于 main() 也是一个函数,因此您会收到链接器错误。

尝试在 main() 之外定义函数。在外部定义后,您可以从 main() 调用它们。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res