I have a header file and a cpp file. In the .h
file I declared a class and a function with returning a reference:
.h
file :
#include <iostream>
class testclass {
Car &createCar(int x, int y);
}
.cpp
file :
#include<testclass.h>
Car testclass:&createCar(int x, int y)
{
....
}
But when I try to access the function in the .cpp
file I get an error:
Declaration is not compatible
The function definition in .cpp file should be compatible with its decleration in .h file so modify it as follows.
.cpp file:
#include"testclass.h"
Car& testclass::createCar(int x, int y)
{
....
}
Note that I modified <testclass.h>
to "testclass.h"
. use the brackets only with the built in headers.
Follow the following line if you want to know why you should use "testclass.h"
instead of <testclass.h>
and which one of them you should use Link
In your .h
file, &
is not a reference to a function. The &
is part of the function's return type. So, the function actually returns a reference to a Car
instance. It would help you to understand it if you actually write it that way:
Car& createCar(int x, int y);
As such, in the .cpp
file, you need to move the &
to the return type to match the declaration:
#include <iostream>
class testclass {
Car& createCar(int x, int y);
};
#include "testclass.h"
Car& testclass::createCar(int x, int y)
{
....
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.