Anlamı "sabit" C yöntem bildirimi son?
Bu gibi bildirimleri const
anlamı nedir? const
kafamı karıştırdı.
class foobar
{
public:
operator int () const;
const char* foo() const;
};
CEVAP
this
işaretçiyi aslında sabit olacak bir yöntem const
anahtar kelime eklemek, ve bu nedenle herhangi bir üye veri değiştirebilirsiniz. (mutable
, daha sonra daha fazla) kullanmadığınız sürece.
const
anahtar iki benzer yöntemler, nesne sabit denir hangisini uygulamak anlamına gelir fonksiyonları imza parçası, ve bir o değil.
#include <iostream>
class MyClass
{
private:
int counter;
public:
void Foo()
{
std::cout << "Foo" << std::endl;
}
void Foo() const
{
std::cout << "Foo const" << std::endl;
}
};
int main()
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
}
Bu çıktı
Foo
Foo const
Olmayan sabit yöntem olamaz inş sürümünde yapmak, örnek üyeleri, değiştirebilirsiniz. Kod için yukarıdaki örnekte yöntem bildirimi aşağıda değiştirirseniz bazı hatalar alırsınız.
void Foo()
{
counter ; //this works
std::cout << "Foo" << std::endl;
}
void Foo() const
{
counter ; //this will not compile
std::cout << "Foo const" << std::endl;
}
Bu 'değişken' ve sabit bir yöntem daha sonra değiştirebilirsiniz. üye olarak bir işareti olabilir, çünkü tam olarak doğru değil, Çoğunlukla iç sayaçları ve şeyler için kullanılır. Bunun çözümü ise aşağıdaki kod olacaktır.
#include <iostream>
class MyClass
{
private:
mutable int counter;
public:
MyClass() : counter(0) {}
void Foo()
{
counter ;
std::cout << "Foo" << std::endl;
}
void Foo() const
{
counter ;
std::cout << "Foo const" << std::endl;
}
int GetInvocations() const
{
return counter;
}
};
int main(void)
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
std::cout << "The MyClass instance has been invoked " << ccc.GetInvocations() << " times" << endl;
}
hangi çıktı
Foo
Foo const
The MyClass instance has been invoked 2 times
&; statik sabit" vs " quot;#d...
Neden anahtar kelime "son" J...
Ne'In arasındaki fark "Norma...
Planlanan " anlamı, özel korumalı&...
Garip " []&; yöntem imzası Java s...