【发布时间】:2014-09-10 00:58:40
【问题描述】:
我正在编写一个带有派生类的简单银行程序,但在包含父类时遇到了Multiple definition of <method name> 错误。
请记住,我昨天刚开始使用 C++ 进行编码,并且从 Java/PHP 开始,处理标头/定义对我来说有点混乱。请纠正您看到的任何错误!
这是我的文件/代码示例:
文件
- Account.h
- Account.cpp(超级)
- ChequingAccount.cpp(儿童)
- SavingsAccount.cpp(儿童)
将父类 (Account.cpp) 包含到任何文件中时,该错误是可重现的。我已经减少了很多代码,但它应该让您了解我如何处理继承。
澄清一下,当我 #include 任何文件 (ChequingAccount.cpp) 的子类工作正常时,继承的函数按预期工作。但是,当我 #include 父类 (Account.cpp) 中断编译器时,所有方法都会出现 Multiple definition of <method name> 错误。
同样,我不确定这是否是正确的方法,但这是我从我找到的教程中了解到的。
代码
Account.h
#ifndef ACCOUNT_H
#define ACCOUNT_H
class Account
{
protected:
double m_balance;
public:
Account(double balance); // Constructor.
virtual ~Account(); // Destructor.
// Accessor Methods.
double getBalance() const;
// Mutator Methods.
virtual void withdrawFunds(double amount);
void depositFunds(double amount);
};
#endif
Account.cpp(超类)
#include "Account.h"
Account::Account(double balance = 0)
{
m_balance = balance;
}
Account::~Account()
{
// TODO: Delete this data structure...
}
double Account::getBalance() const
{
return m_balance;
}
void Account::withdrawFunds(double amount)
{
m_balance -= amount;
}
void Account::depositFunds(double amount)
{
m_balance += amount;
}
ChequingAccount.cpp(儿童)
#include "Account.h"
class ChequingAccount: public Account
{
public:
ChequingAccount(int id, int userId, double balance) : Account(id, balance){};
void withdrawFunds(double amount)
{
// Override parent method.
}
};
任何帮助将不胜感激!谢谢!
【问题讨论】:
-
当您说“将父类 (Account.cpp) 包含到任何文件中”时,究竟是什么意思。?如果你的意思是你做
#include "Account.cpp",那么这可能就是问题所在。 -
@uesp 是的,就是这样。这样做有什么问题?我不打算使用父类,但我想知道为什么包含该文件时会出错?这更像是一个“为什么”的问题,而不是“我该如何解决这个问题”。
-
@user3745117 你真的这样做了吗?发布的代码显示了
#include的正确用法,以及.h头文件。 -
@Potatoswatter 不,我的代码中没有这个,但我想知道为什么在我执行
#include时会出错。
标签: c++ inheritance include multiple-definition-error