I'm trying to create a method in a C++ class that can be called without creating an instance of the class (like a static method in Java), but I keep running into this error: error: expected unqualified-id before ‘.’ token
Here's the .cpp file I'm trying to compile:
using namespace std;
#include <iostream>
class Method {
public:
void printStuff(void) {
cout << "hahaha!";
}
};
int main(void){
Method.printStuff(); // this doesn't work as expected!
return 0;
}
A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.
The static data members are basically same in Java and C++. The static data members are the property of the class, and it is shared to all of the objects.
You can use the full power of inheritance and overriding since your methods are no longer static. You can use the constructor to do any initialisation, including associating SQL with the table (SQL that your methods can use later). This should make all your problems above go away, or at least get much simpler.
A static method in Java (also called class method) is a method that belongs to the class and not the instance. Therefore, you can invoke the method through the class instead of creating an instance first and calling the method on that instance.
In C++ it's
Method::printStuff();
and you have to declare the method as static
.
class Method{
public:
static void printStuff(void){
cout << "hahaha!";
}
};
::
is called the scope resolution operator. You can call the method with .
if it's on a class instance, but the instance is not required (it being static and all...).
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