Pra*_*ari 1 c++ java language-features compiler-errors
我是Java的新手(在Android上工作).我见过代码,
new DownloadFilesTask().execute(url1, url2, url3);
Run Code Online (Sandbox Code Playgroud)
这里无名(我不确定我是否使用了正确的术语)对象用于调用DownloadFilesTask对象的execute方法.
同样我尝试使用C++,以下是代码片段.
#include <iostream>
#include <vector>
using namespace std;
class Sam
{
public:
void Access()
{
cout<<"Access";
}
};
int main(int argc, char* argv[])
{
(new Sam())->Access; //for Access method intillesence is working fine
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试运行此代码时,我收到编译错误,
错误1错误C3867:'Sam :: Access':函数调用缺少参数列表; 使用'&Sam :: Access'创建指向成员的指针c:\ users \new-user\documents\visual studio 2012\projects\autoexample\autoexample\autoexample.cpp 18 1 autoExample
我不明白错误的含义和原因.这种类型的代码在C++中是否可行?
谢谢.
正如在评论中所说的那样,你缺少调用该方法所需的括号.
Access()
// ^^ These
Run Code Online (Sandbox Code Playgroud)
但是,这里要解决的一个更重要的问题是你的使用new.不要像现在使用它一样使用它.通过这种方式使用它,你创造了一个你永远不会希望收回的内存泄漏,因为你永远不会有机会使用delete它[1](除非你关闭你的程序......).
要在C++中使用临时对象,只需使用基于堆栈的自动存储对象(换句话说,普通对象):
Sam().Access();
//^^^^^ This creates the temporary object
Run Code Online (Sandbox Code Playgroud)
但是,您仍然必须小心不要在后续语句中使用该临时语句,这是将它们与引用混合时经常遇到的问题.
Sam& bad_sam = Sam().I_Return_A_Reference_To_This_Object();
bad_sam.Access(); // Oh no!
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,创建的临时对象Sam()将在语句结束时被销毁(因此是临时的).bad_sam.Access();将是非法的,将导致未定义的行为.
[1] Ahem说语言律师.当然你可以用delete this;......对OP:不要!
| 归档时间: |
|
| 查看次数: |
124 次 |
| 最近记录: |