簡體   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