编译器无法识别在类声明之外定义的方法

compiler not recognizing methods defined outside the class declaration

本文关键字:定义 方法 声明 识别 编译器      更新时间:2023-10-16

C++的新功能。我在这里遇到了一个问题,我制作了一个银行账户程序,该程序在一个名为"account"的类中定义了 withdraw(( 和 deposit(( 等函数。因此,我在另一个文件(account.h(中定义了我的类,我也在类本身中定义了 withdraw((,但在"account.cpp"文件中定义了类外部的 deposit(( 函数。当我编译它时,我收到以下错误 -undefined reference to 'account::deposit(int)'我不是专家,但我认为它没有认识到我定义了 define(( 函数 int account.cpp.我也使用 vscode(如果有帮助的话,idk(。

这是代码- 主.cpp

#include <iostream>
#include <string>
#include <vector>
#include "account.h"
int main()
{
account Ajay_bank;
if (Ajay_bank.withdraw(1000))
{
std::cout << "withdraw successfuln";
}
else
{
std::cout << "withdraw failed";
}
if (Ajay_bank.deposit(2000))
std::cout << "Deposit successful";
else
std::cout << "[error - NET404]:try again later";

}

帐户.cpp-

#include "account.h"

bool account::deposit (int amount)
{
balance += amount;
return true;
}

帐户.h-

#ifndef _ACCOUNT_H
#define _ACCOUNT_H
#include <string>
class account
{
private:
std::string name;
int balance {200};
int credit_score {};
public:
bool withdraw (int amount)
{
if (balance - amount >= 0)
{
balance -= amount;
return true;
}
else
return false;
}
bool deposit (int amount);
};
#endif

谢谢。

在编译多个源文件 (.cpp( 时,您应该使用该文件进行编译。

g++ main.cpp account.cpp -o main

然后像这样运行它:

./main

如果您尝试使用该命令,则可以成功运行