繁体   English   中英

C++ 在cpp 中使用头文件中的引用函数?

[英]C++ Using a reference function from header file in the cpp?

我有一个头文件和一个 cpp 文件。 .h文件中,我声明了一个类和一个返回引用的函数:

.h文件

#include <iostream>
class testclass {
    Car &createCar(int x, int y);
}

.cpp文件

#include<testclass.h>
Car testclass:&createCar(int x, int y)
{
  ....
}

但是当我尝试访问.cpp文件中的函数时,出现错误:

声明不兼容

.cpp 文件中的函数定义应该与其在 .h 文件中的声明兼容,因此修改如下。

.cpp 文件:

#include"testclass.h"
Car& testclass::createCar(int x, int y)
{
  ....
}

请注意,我将<testclass.h>修改为"testclass.h" 仅将括号与内置标题一起使用。

如果您想知道为什么应该使用"testclass.h"而不是<testclass.h>以及您应该使用其中的哪一个Link

在您的.h文件中, &不是对函数的引用。 &是函数返回类型的一部分。 因此,该函数实际上返回对Car实例的引用。 如果你真的这样写,它会帮助你理解它:

Car& createCar(int x, int y);

因此,在.cpp文件中,您需要将&移动到返回类型以匹配声明:

#include <iostream>

class testclass {
    Car& createCar(int x, int y);
};
#include "testclass.h"

Car& testclass::createCar(int x, int y)
{
  ....
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM