Я не кодировал в c++ в течение некоторого времени и застрял, когда попытался скомпилировать этот простой фрагмент:
class A
{
public:
void f() {}
};
int main()
{
A a1;
a1.f(); // works fine
A *a2 = new A();
a2.f(); // this doesn't
}
Я не кодировал в c++ в течение некоторого времени и застрял, когда попытался скомпилировать этот простой фрагмент:
class A
{
public:
void f() {}
};
int main()
{
A a1;
a1.f(); // works fine
A *a2 = new A();
a2.f(); // this doesn't
}
Это указатель, поэтому вместо этого попробуйте:
a->f();
В основном оператор .
(используется для доступа к полям и методам объекта) используется для объектов и ссылок, поэтому:
A a;
a.f();
A& ref = a;
ref.f();
Если у вас есть тип указателя, вы должны сначала разыменовать его, чтобы получить ссылку:
A* ptr = new A();
(*ptr).f();
ptr->f();
a->b
обычно является сокращением для (*a).b
.
operator->
может быть перегружен, что особенно используется интеллектуальными указателями. Когда вы используете умные указатели, вы также используете ->
для ссылки на указанный объект:
auto ptr = make_unique<A>();
ptr->f();
Разрешить анализ.
#include <iostream> // not #include "iostream"
using namespace std; // in this case okay, but never do that in header files
class A
{
public:
void f() { cout<<"f()\n"; }
};
int main()
{
/*
// A a; //this works
A *a = new A(); //this doesn't
a.f(); // "f has not been declared"
*/ // below
// system("pause"); <-- Don't do this. It is non-portable code. I guess your
// teacher told you this?
// Better: In your IDE there is prolly an option somewhere
// to not close the terminal/console-window.
// If you compile on a CLI, it is not needed at all.
}
Как общий совет:
0) Prefer automatic variables
int a;
MyClass myInstance;
std::vector<int> myIntVector;
1) If you need data sharing on big objects down
the call hierarchy, prefer references:
void foo (std::vector<int> const &input) {...}
void bar () {
std::vector<int> something;
...
foo (something);
}
2) If you need data sharing up the call hierarchy, prefer smart-pointers
that automatically manage deletion and reference counting.
3) If you need an array, use std::vector<> instead in most cases.
std::vector<> is ought to be the one default container.
4) I've yet to find a good reason for blank pointers.
-> Hard to get right exception safe
class Foo {
Foo () : a(new int[512]), b(new int[512]) {}
~Foo() {
delete [] b;
delete [] a;
}
};
-> if the second new[] fails, Foo leaks memory, because the
destructor is never called. Avoid this easily by using
one of the standard containers, like std::vector, or
smart-pointers.
Как правило: если вам нужно самостоятельно управлять памятью, обычно есть супервайер-менеджер или альтернатива, которые уже существуют по принципу RAII.
Резюме: вместо af();
должно быть a->f();
В основной вы определили как указатель на объект A, так что вы можете получить доступ к функциям с помощью ->
оператора.
Альтернативный, но менее читаемый способ - (*a).f()
af()
можно было бы использовать для доступа к f(), если бы a было объявлено как: A a;
a
- указатель. Вам нужно использовать ->
, а не .