我想知道是否可以从另一个文件访问非成员函数。也就是说,在 .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.hpp
或Shape.cpp
文件的情况下使用?
我面临一个非常具体的问题,我正在为一个类编写测试,但需要为非成员函数编写测试。