gpt4 book ai didi

C++:包含父类时出现多重定义错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:52:42 26 4
gpt4 key购买 nike

我正在用派生类编写一个简单的银行程序,我遇到了一个 Multiple definition of <method name>包含父类时出错。

请记住,我昨天才开始用 C++ 编码,从 Java/PHP 转移过来,处理 header /定义对我来说有点困惑。请更正您看到的任何错误!

这是我的文件/代码示例:

文件

  • 账户.h
  • Account.cpp( super )
  • ChequingAccount.cpp( child )
  • SavingsAccount.cpp( child )

当将父类 (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(父类(super class))

#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.
}
};

任何帮助将不胜感激!谢谢!

最佳答案

当您 #include "some file.cpp"时,您是在指示编译器将该 cpp 文件的内容复制到程序中的那个位置。这将创建“某些文件”的两个编译版本,这将导致“多个定义”。

关于C++:包含父类时出现多重定义错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25755772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com