Mesaje recente

Members
Stats
  • Total Posts: 17,786
  • Total Topics: 1,234
  • Online today: 302
  • Online ever: 318
  • (17 October 2024, 13:29)
Users Online
Users: 0
Guests: 149
Total: 149

Metoda statica in C++

Started by kquizak, 01 November 2006, 23:15

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

kquizak

va intreb o chestie..sa nu radeti...
in c++ se poate apela metoda direct prin numele clasei,fara ca ea sa fie declarata static?
network-tools.ath.cx ---nmap yourself

kman

Quote from: kquizak on 01 November 2006, 23:15
va intreb o chestie..sa nu radeti...
in c++ se poate apela metoda direct prin numele clasei,fara ca ea sa fie declarata static?

NU, ca sa poti apela o metoda dintr-o clasa fara sa ai clasa instantiata, metoda trebuie sa fie statica altfel o sa-ti crape la compilare.

Ca sa-ti ilustrez:

Code (cpp) Select
#include <iostream>

using namespace std;

class a {
public:
        void cd() { cout << "eject" << endl; } ;
};

int main() {
        a *b = new a();
        b->cd();
        a::cd();
}


kman@dracula:~$ g++ a.cpp
a.cpp: In function 'int main()':
a.cpp:13: error: cannot call member function 'void a::cd()' without object


Acelasi cod, doar ca metoda e statica:

Code (cpp) Select
#include <iostream>

using namespace std;

class a {
public:
        static void cd() { cout << "eject" << endl; } ;
};

int main() {
        a *b = new a();
        b->cd();
        a::cd();
}


kman@dracula:~$ g++ a.cpp
kman@dracula:~$ ./a.out
eject
eject