The following code is part of a slide in my C++ Class. IntelliSence is giving me errors and I don't know why. Not sure why it doesnt like the Constructor and Destructor. Can Someone please Help?
class Vehicle {
friend void guest();
private:
string make;
string model;
int year;
public:
void Vehicle();
void Vehicle(string, string, int);
void ~Vehicle();
string getMake();
}
void guest() {
cout << make;
}
1) IntelliSense: member function with the same name as its class must be a constructor
2) IntelliSense: member function with the same name as its class must be a constructor
3) IntelliSense: return type may not be specified on a destructor
constructors and destructors don't have return types! Should be:
Vehicle();
Vehicle(string, string, int);
~Vehicle();
You need to pass an argument to your function:
void guest(const Vehicle &v)
{
cout << v.make; //friend allows you to access 'make' directly
}
Of course you must change the friend
declaration accordingly
And don't forget ;
at the end of your class
EDIT
Full code that works:
class Vehicle {
friend void guest(const Vehicle &v);
private:
string make;
string model;
int year;
public:
Vehicle() {}
Vehicle(string make, string model, int year) : make(make), model(model), year(year) {}
~Vehicle() {}
string getMake() const {return make;}
};
void guest(const Vehicle &v) {
cout << v.make;
}
int main()
{
guest(Vehicle("foo", "bar", 10));
return 0;
}
The error messages are actually pretty good in this case if you understand them.
void Vehicle();
because the "method" has the same name as the class, your Intellisense thinks it should be a construtor. It's right! Constructors don't have return types, so make it:
Vehicle();
Similarly:
void Vehicle(string, string, int);
also appears to be a constructor because the name of the "method" is the same as the class. Just because it has parameters doesn't make it special. It should be:
Vehicle(string, string, int);
Deconstructors don't have return types either, so
void ~Vehicle();
should be:
~Vehicle();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With