编译器无法识别在类声明之外定义的方法
compiler not recognizing methods defined outside the class declaration
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
如果您尝试使用该命令,则可以成功运行
相关文章:
- 在父类中为多个子类定义方法
- 在.cpp文件中定义方法而不是在 C++ 的 .h 文件中定义方法时,如何提高代码的性能?
- 对已定义方法的未定义引用
- 需要派生的类来定义方法
- 在某些名称空间中定义方法时,在全局名称空间中声明
- 在类 C++ 中重定义方法
- 这两种定义方法的样式之间是否存在差异
- 对已定义方法的未定义引用、标头中的声明和源匹配
- 如果未在类 c++ 中定义方法,如何在类对象上使用方法
- 在为嵌入式类定义方法时,有没有办法避免重复包含类
- 有关C++中一个或多个乘法定义方法的错误
- 在 cpp 文件中定义方法时未解析外部,但在标头中定义时未解析
- 是否允许所有未使用的未定义方法
- 如何在声明之外为专门用于无参数的可变模板类定义C++方法
- 什么是编程语言为派生类重新定义方法的能力
- 在C++中,在类定义内部或外部定义方法体是否更为传统
- 向std::vector或typdef添加自定义方法
- 如果在头文件中定义方法,内联关键字有什么用?
- C++ 我知道数组长度,但想知道是否是一种更简洁的数组元素定义方法
- 在类作用域内定义方法时,除非在原始 cpp 文件中的其他位置调用方法,否则项目不会编译