我have't用C ++编写了一段时间,我卡住了,当我试图编译这个简单的代码片段:
class A
{
public:
void f() {}
};
int main()
{
{
A a;
a.f(); // works fine
}
{
A *a = new A();
a.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->
可以被重载,这是值得注意的是使用智能指针。当you're using smart pointers,那么你也可以使用->
指尖锐的物体:
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.
作为一个经验法则:如果你需要在自己的管理内存,一般是superiour经理或替代现有则已,一后面的RAII原则。
摘要:与其a.f();
应该a->f();
在主要已经定义了一个作为指针到对象A的,这样就可以访问使用->
操作者的功能。
可替换,但不可读的方式是(*a).f()
a.f()
本来是用来访问F(),如果被声明为:A a;
a
是一个指针。您需要use->
,不.