我已经用c ++编写了一段时间,当我尝试编译这个简单的代码片段时我遇到了困难
#include "iostream"
using namespace std;
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"
system("pause");
}
答案 0 :(得分:133)
这是一个指针,所以请尝试:
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();
答案 1 :(得分:13)
允许分析。
#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原则。
答案 2 :(得分:8)
摘要:而不是a.f();
应该是a->f();
在主要内容中,您已将 a 定义为指向 A 的对象的指针,因此您可以使用->
访问函数操作
替代,但不太可读的方式是(*a).f()
a.f()
可能已用于访问f(),如果 a 被声明为:
A a;
答案 3 :(得分:6)
a
是一个指针。您需要使用->
,而不是.