c++:覆盖运算符时的多个定义
c++: Multiple definitions when overriding operators
我正在努力实现一个有理数的类,这当然涉及覆盖"=="和"!="等常见运算符。 我很确定我缺少某个地方有一个愚蠢的错误,请不要犹豫,询问我没有提供的任何文件。 谢谢!
理性.hpp:
#ifndef RATIONAL_HPP
#define RATIONAL_HPP
#include "test.hpp"
#include <cstdlib>
#include <iosfwd>
#include <iostream>
#include <assert.h>
// Mathematical helper functions.
//
// NOTE: These are defined in rational.cpp.
int gcd(int, int);
int lcm(int, int);
// Represents a rational number. The rational numbers are the set of
// numbers that can be represented as the quotient of two integers.
struct Rational
{
// TODO: Define the following:
// 1. A default constructor
int n;
int d;
Rational()
:n(0), d(1) {}
// 2. A constructor that takes an integer value
Rational(int num)
:n(num), d(1){}
// 3. A constructor that takes a pair of values
Rational(int numer, int denom)
:n(numer), d(denom) {
assert( d != 0);
int gcdnum;
if ((numer % denom) != 0){
//do nothing
}else{
gcdnum = gcd(numer, denom);
numer /= gcdnum;
denom /= gcdnum;
Rational(numer, denom);
}
}
// Returns the numerator.
int num() const {
return n;
}
// Returns the denominator
int den() const {
return d;
}
};
bool operator==(Rational a, Rational b){
return (a.n == b.n && a.d == b.d);
}
bool operator!=(Rational a, Rational b){
return (a.n != b.n && a.d != b.d);
}
bool operator < (Rational a, Rational b){
int lcdNum = lcm(a.d, b.d);
int newAN, newBN; //allows for comparisons without altering actuial value
newAN = a.n * lcdNum;
newBN = b.n * lcdNum;
return newAN < newBN;
}
bool operator > (Rational a, Rational b){
int lcdNum = lcm(a.d, b.d);
int newAN, newBN; //allows for comparisons without altering actuial value
newAN = a.n * lcdNum;
newBN = b.n * lcdNum;
return newAN > newBN;
}
bool operator <= (Rational a, Rational b){
int lcdNum = lcm(a.d, b.d);
int newAN, newBN; //allows for comparisons without altering actuial value
newAN = a.n * lcdNum;
newBN = b.n * lcdNum;
return newAN <= newBN;
}
bool operator >= (Rational a, Rational b){
int lcdNum = lcm(a.d, b.d);
int newAN, newBN; //allows for comparisons without altering actuial value
newAN = a.n * lcdNum;
newBN = b.n * lcdNum;
return newAN >= newBN;
}
// 3. The standard arithmetic operators
// - r1 + r2
// - r1 - r2
// - r1 * r2
// - r1 / r2
// - r1 / r2
Rational operator + (Rational a, Rational b){
int lcdNum = lcm(a.d, b.d);
int newAN, newBN; //allows for comparisons without altering actuial value
newAN = a.n * lcdNum;
newBN = b.n * lcdNum;
Rational c((newAN + newBN), (a.d * lcdNum));
return c;
}
Rational operator - (Rational a, Rational b){
int lcdNum = lcm(a.d, b.d);
int newAN, newBN; //allows for comparisons without altering actuial value
newAN = a.n * lcdNum;
newBN = b.n * lcdNum;
Rational c((newAN + newBN), (a.d * lcdNum));
return c;
}
Rational operator * (Rational a, Rational b){
Rational c((a.n * b.n), (a.d * b.d));
return c;
}
Rational operator / (Rational a, Rational b){
Rational c((a.n * b.d), (a.d * b.n)); //multiplies by the reciprocal
return c;
}
std::ostream& operator<<(std::ostream&, Rational);
std::istream& operator>>(std::istream&, Rational&);
#endif
理性.cpp:
//
// rational.hpp: Definition of rational class and its interace.
#include "rational.hpp"
#include <iostream>
// -------------------------------------------------------------------------- //
// Helper functions
// Compute the GCD of two integer values using Euclid's algorithm.
int
gcd(int a, int b)
{
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
// Compute the LCM of two integer values.
int
lcm(int a, int b)
{
return (std::abs(a) / gcd(a, b)) * std::abs(b);
}
// -------------------------------------------------------------------------- //
// Rational implementation
// TODO: Make this print integers when the denominator is 1.
std::ostream&
operator<<(std::ostream& os, Rational r)
{
if(r.den() == 1){
return os << r.num();
}else{
return os << r.num() << '/' << r.den();
}
}
// TODO: Make this read integer values if no '/' is given as a separator.
// You may assume that there is no space between the numerator and the
// slash. Hint, find and read the reference documentation for istream::peek().
std::istream&
operator>>(std::istream& is, Rational& r)
{
int p, q;
char c;
is >> p;
c = is.peek();
if (c == '/'){
is >> c >> q;
if (!is)
return is;
// Require that the divider to be a '/'.
if (c != '/') {
is.setstate(std::ios::failbit);
return is;
}
// Make sure that we didn't read p/0.
if (q == 0) {
is.setstate(std::ios::failbit);
return is;
}
r = Rational(p, q);
return is;
}else{
is.setstate(std::ios::failbit);
}
}
RC.cpp:
// main.cpp: rational number test suite
#include "rational.hpp"
#include <iostream>
#include <iomanip>
#include <unistd.h>
int
main()
{
// Determine if input is coming from a terminal.
bool term = isatty(0);
// This will continue reading until it reaches the end-of-input.
// If you are using this interactivly, type crtl-d to send the
// end of input character to the terminal.
while (std::cin) {
Rational r1;
Rational r2;
std::string op;
if (term)
std::cout << "> ";
std::cin >> r1 >> op >> r2;
if (!std::cin)
break;
// FIXME: Add all of the other overlaoded operators by adding
// cases for each of them.
if (op == "==")
std::cout << std::boolalpha << (r1 == r2) << 'n';
else if (op == "!=")
std::cout << std::boolalpha << (r1 != r2) << 'n';
else if (op == "<")
std::cout << std::boolalpha << (r1 < r2) << 'n';
else if (op == ">")
std::cout << std::boolalpha << (r1 > r2) << 'n';
else if (op == "<=")
std::cout << std::boolalpha << (r1 <= r2) << 'n';
else if (op == ">=")
std::cout << std::boolalpha << (r1 >= r2) << 'n';
else if (op == "+")
std::cout << (r1 + r2) << 'n';
else if (op == "-")
std::cout << (r1 - r2) << 'n';
else if (op == "*")
std::cout << (r1 * r2) << 'n';
else if (op == "/")
std::cout << (r1 / r2) << 'n';
else
std::cerr << "invalid operator: " << op << 'n';
}
// If we got to the end of the file without fatal errors,
// return success.
if (std::cin.eof())
return 0;
// Otherwise, diagnose errors in input and exit with an error
// code.
if (std::cin.fail()) {
std::cerr << "input errorn";
return 1;
}
return 0;
}
每个#include
rational.hpp
的翻译单元都将获得比较运算符函数的定义,这肯定会在链接时导致重复的定义。
尝试在它们前面粘贴"内联"关键字。
你在rational.hpp
中定义函数,这意味着每个翻译单元都包含rational.hpp
将包含定义,并导致重复的定义错误。
应将声明和定义拆分为头文件和实现文件。如
理性.hpp:
bool operator==(Rational a, Rational b);
bool operator!=(Rational a, Rational b);
...
理性.cpp:
bool operator==(Rational a, Rational b){
return (a.n == b.n && a.d == b.d);
}
bool operator!=(Rational a, Rational b){
return (a.n != b.n && a.d != b.d);
}
...
顺便说一句:operator!=
中的逻辑似乎是错误的,我想可能是return (a.n != b.n || a.d != b.d);
。无论如何,正如@NickyC建议的那样,最好将其return !(a == b);
实现以避免重复。
相关文章:
- 使用子类覆盖基类中定义的函数
- 如何使用用户定义的函数覆盖 C lib 函数,如 _sbrk?
- 为什么销毁被放置 new 覆盖的对象不是未定义的行为?
- 无法键入 def std::chrono::microseconds 以覆盖其定义以更改其基础类型
- 当在Python中定义__str__时,如何将C 的标准全局函数覆盖
- 使用自定义 QSortFilterProxyModel 覆盖哪些函数
- 仅覆盖自定义数据架构的迭代器的操作员*()
- 如何在CMake中覆盖宏定义
- C++自定义全局新建/删除覆盖系统库
- 自定义堆栈分配器,覆盖Delete
- c++:覆盖运算符时的多个定义
- 覆盖和扩展数组或矩阵,而不在特征中定义其大小
- 在链接时弱定义函数,并测试覆盖
- 如何覆盖自定义Firemonkey控件的点击事件
- 如何覆盖已定义类型的 ostream <<运算符 如何使下拉子菜单直接显示在其父菜单下方<li>?
- 如何覆盖类中定义的enum的std::hash
- 当显式调用非默认函数时,覆盖自定义字符串失败
- 如何以非内联方式定义模板覆盖的功能
- 为什么 Boost 使用全局函数覆盖来实现自定义验证程序"Program Options"
- 我可以覆盖C++/MFC项目中全局定义的API吗