单独的类声明和方法定义文件问题
Separate class declaration and method definition files problem
我正在尝试为我的项目使用单独的文件,包括声明类方法的头文件和用于定义方法.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')
你有一个编译错误,因为你的主要对operator+
和operator<<
一无所知。
写
Point operator+(Point& pt1, Point& pt2);
std::ostream& operator<<(std::ostream& os, const Point& pt);
h
文件中或转发声明它们 在main
文件中。
还有一件事。您应该在<< ", " <<
中使用 "。
相关文章:
- 告诉CMake链接到自定义文件夹中的Boost
- 通过cMake使用具有自定义文件扩展名的共享库
- 威纳派读取自定义文件或文件夹的所有访问权限
- 使用命令列表解析自定义文件
- 单独的类声明和方法定义文件问题
- Qt解析自定义文件格式
- 将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
- FAT32和NTF中的自定义文件属性
- 如何在没有"fatal error: Wt/WApplication: No such file or directory"的情况下将wt安装到自定义文件夹中
- C++ while 循环在自定义文件结构中
- QT C 读取自定义文件结构
- gcc 是否有编译指示来定义文件类型/编译器
- C/C++ 中的跨平台自定义文件头
- 使用头文件和类定义文件时未解决的外部符号错误
- 将此c++代码分解为单独的类规范文件和函数定义文件
- 自定义文件类中fstream对象的生存期
- 如何使用BinaryReader类使用C#读取自定义文件(C++)
- 提供带有libjpeg的自定义文件IO
- C++模块定义文件头内联符号
- 错误:未定义文件中的第一个引用符号