我正在学习C ++而我正在尝试理解const。我一直在使用const和我的getter以及显示函数来保证在获取和发送显示时不会改变值。
我正在开发一个使用多个header和.cpp文件的程序,在程序的这一部分之前我没有遇到任何问题:
该计划的这一部分收集产品的信息。它有3个显示选项。所有3个显示都设置为const,我没有错误。
在我的头文件中,我有这两个原型:
float getShippingCost() const{return shippingCost;}
float getTotalPrice() const{return totalPrice;}
在同一个文件中,我有其他getter和setter,其中没有一个看起来有错误,而且大多数getter都是const。
在我的.cpp文件中,我有方法:
float Product :: getShippingCost() {
insert code here, proven to work before I started working with
const and other files, the return as shown earlier is in the .h file,
the same is true for the next method.}
float Product :: getTotalCost(){insert code here}
如果我在.cpp文件中设置方法,我会收到重新声明错误。如果我删除const,我会在.h错误中找到没有原型。我已经尝试了所有我能想到的事情,包括将返回移动到.cpp文件。
有人可以解释一下这是如何运作的吗?我以为我理解这一点,但现在我只是感到困惑。
我的代码如下:
#include <iostream>
#include <iomanip>
using namespace std;
class Wallet
{
private:
float money;
float dollars;
float cents;
public:
float getMoney() const {return money;}
void display()const;
};
float Wallet::getMoney() const { money += dollars + cents; }
void Wallet::display() const { cout << "You have $" << money << endl; }
答案 0 :(得分:2)
如果没有来自解释的最小示例,请在头文件中说明:
float getShippingCost() const{return shippingCost;}
不是宣言,是宣言和实施。
float getShippingCost() const;
仅为声明
在你的.cpp中你提到你有:
float Product:: getShippingCost() const{insert code here}
这是另一种实现方式。这不是const
的问题,它说它是一个重新声明。要解决此问题,请将标题更改为仅包含
float getShippingCost() const;
float getTotalPrice() const;
答案 1 :(得分:0)
这与我对你的问题的理解有关。发布Minimal, Complete, and Verifiable example会更有帮助,因此我们确切知道您正在使用的内容。
当您使用const
关键字声明成员函数时,必须在声明和定义中使用它,如下所示:
标题.h:
class Product {
float getTotalCost() const;
float m_cost;
}
在源.cpp:
Product::getTotalCost() const // <- remember to add the keyword in both
{
return m_cost;
}
除此之外,你永远不应该使用浮点数来筹集资金!使用固定点十进制类或整数除以。