我已经有一段时间没有用C ++编写代码了,当我尝试编译这个简单的代码片段时,我陷入了困境:
class A
{
public:
void f() {}
};
int main()
{
{
A a;
a.f(); // works fine
}
{
A *a = new A();
a.f(); // this doesn't
}
}
Answers:
它是一个指针,所以尝试:
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原则。