0

我想知道是否可以从另一个文件访问非成员函数。也就是说,在 .cpp 而不是在其头文件中声明和定义的函数。

我做了一个简短的例子来说明我在问什么:

我有一个非常基本的头文件Shape.hpp,它只声明了一个将打印单词“Square”的函数</p>

#ifndef SHAPE_HPP
#define SHAPE_HPP

class Shape
{
public:
    void printSquare();
};

#endif

Shape.cpp文件中,我定义了printSquare()函数,但我还声明并定义了一个名为的新函数printCircle()

#include “Shape.hpp”
#include <iostream>

void Shape::printSquare()
{
    std::cout << “Square”;
}

void printCircle()
{
    std::cout << “Circle”;
}

这些文件是微不足道的,但我试图以一种非常简单的方式展示我的问题。

现在,在我的Main.cpp文件中,我尝试同时调用 theprintSquare()printCircle()方法。

#include “Shape.hpp”

int main()
{
    Shape shape;
    shape.printSquare();
    //shape.printCircle(); <—- this will give an error because printCircle() is not visible outside of Shape.cpp
}

有没有办法让我的Main.cpp文件能够在printCircle()不修改我的Shape.hppShape.cpp文件的情况下使用?

我面临一个非常具体的问题,我正在为一个类编写测试,但需要为非成员函数编写测试。

4

1 回答 1

2

使用 extern 关键字,在要使用的文件中声明 extern void printCircle()。它让编译器知道该函数是在其他地方定义的。

#include “Shape.hpp”

extern void printCircle();

int main()
{
    // call extern function
    printCircle();

    Shape shape;
    shape.printSquare();
    printCircle();
}
于 2020-03-11T16:30:42.810 回答