【问题标题】:Separate class declaration and method definition files problem [duplicate]单独的类声明和方法定义文件问题[重复]
【发布时间】:2019-08-13 20:24:37
【问题描述】:

我正在尝试为我的项目使用单独的文件,包括用于声明类方法的头文件和用于定义方法的 .cpp 文件。

但是,强制执行隐藏的方法实现会出错并且无法编译代码。

文件向量.h

#ifndef VECTOR_H
#define VECTOR_H


#include <iostream>

class Point
{
private:
    float x;
    float y;

public:
    Point(float x, float y);
    float get_x() const;
    float get_y() const;

};

#endif // VECTOR_H

文件向量.cpp

#include "vector.h"

Point::Point(float x, float y): x(x), y(y) {}

float Point::get_x() const
{
    return x;
}

float Point::get_y() const
{
    return y;
}

Point operator+(Point& pt1, Point& pt2)
{
    return {pt1.get_x() + pt2.get_x(), pt1.get_y() + pt2.get_y()};
}

std::ostream& operator<<(std::ostream& os, const Point& pt)
{
    os << '(' << pt.get_x() << ', ' << pt.get_y() << ')';
    return os;
}

文件源.cpp

#include "vector.h"

int main()
{
    Point p1(1.4, 2.324), p2(2.004, -4.2345);

    std::cout << p1 << '\n';
    std::cout << p2 << '\n';
    std::cout << p1 + p2 << '\n';

    return 0;
}

最后我得到:

error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'Point')

error: no match for 'operator+' (operand types are 'Point' and 'Point')

【问题讨论】:

  • 我没有看到在头文件中声明了&lt;&lt; 运算符。 + 运算符也是如此。它在.cpp 文件中定义,但头文件的全部目的是声明头文件中定义的内容,以便其他翻译单元知道它们存在,对吧?您如何期望.cpp 知道另一个.cpp 中定义的自定义运算符或函数,除非它在某处明确声明。哦,运算符最好也带const 参数,否则它们将无法处理临时对象。
  • 缺少const for Point operator+(Point&amp; pt1, Point&amp; pt2),-> Point operator+(const Point&amp; pt1, const Point&amp; pt2)

标签: c++ oop


【解决方案1】:

你有一个编译错误,因为你的 main 对 operator+operator&lt;&lt; 一无所知。

Point operator+(Point& pt1, Point& pt2);
std::ostream& operator<<(std::ostream& os, const Point& pt);

h 文件中或在main 文件中转发声明它们。

还有一件事。您应该在&lt;&lt; ", " &lt;&lt; 中使用“”。

【讨论】:

  • 宁愿将声明添加到标题中,而不是将它们直接放在 main 中。标题在未来更有用。
  • 为什么我不能在 public of class 中添加 Point operator+(Point&amp; pt1, Point&amp; pt2); std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Point&amp; pt); 行?
  • @Pr.Germux,你可以。然而签名会有所不同。我会在稍后发布答案。
  • @Pr.Germux,对于operator+,它将是Point operator+(const Point&amp; lhs) const。顺便说一句,把逻辑上是const的所有东西都变成const
  • @Pr.Germux,对于operator&lt;&lt;,请阅读stackoverflow.com/questions/9351166/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多