我正在学习 C++,并且正在努力理解常量。我一直将 const 与我的 getter 和显示函数一起使用,以防止值在获取和发送到显示时发生变化。
我正在开发一个使用多个头文件和 .cpp 文件的程序,在程序的这一部分之前我对 const 没有任何问题:
程序的这一部分收集产品的信息。它有 3 个显示选项。所有 3 个显示都已设置为 const,我在那里没有错误。
在我的头文件中,我有这两个原型(prototype):
float getShippingCost() const{return shippingCost;}
float getTotalPrice() const{return totalPrice;}
在同一个文件中,我还有其他的 getter 和 setter,它们似乎都没有错误,而且大多数 getter 都是常量。
在我的 .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 错误中得到一个 no prototype found 。我已经尝试了所有我能想到的方法,包括将返回移动到 .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; }
最佳答案
没有解释中的最小示例,在您的头文件中您说您有:
float getShippingCost() const{return shippingCost;}
不是声明,是声明和实现。
float getShippingCost() const;
只是一个声明
在你的 .cpp 中你提到你有:
float Product:: getShippingCost() const{insert code here}
这是另一种实现方式。这不是 const
的问题,而是它所说的 re 声明。要解决此问题,请将 header 更改为仅包含
float getShippingCost() const;
float getTotalPrice() const;
关于c++ const 不适用于头文件原型(prototype) - 重新声明或无原型(prototype)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46782315/