c++ - 单独的类声明和方法定义文件问题

标签 c++ oop

<分区>

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

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

文件vector.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

文件vector.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')

最佳答案

你有一个编译错误,因为你的 main knows nothing about operator+operator<< .

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

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

还有一件事。您应该在 << ", " << 中使用“” .

关于c++ - 单独的类声明和方法定义文件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57484864/

相关文章:

c++ - 多平台C++项目结构

c++ - Linux wxwidgets 中的 Freeze() 和 Thaw() 函数问题

java - 抽象类,OOP

php - 使用 AJAX 调用 PHP 类方法

javascript - 使用数字作为 javascript 对象元素的名称

c++ - 使用Vector函数C++从文件中读取特定数据

c++ - 将 Fortran 字符串引用传递给 C++ 和 C++ 设置值

c++ - AVL 二叉搜索树旋转 C++

java - 希望在传递给父构造函数之前初始化成员

Javascript child 的构造函数名称