这是'type variableofType()'函数还是对象? [英] Is this' type variableofType()' function or object?

查看:406
本文介绍了这是'type variableofType()'函数还是对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
class name
{
public:
    int a;
    name():a(0){};
};
void add(name * pname)
{
    pname = NULL;
}
int main()
{
    name varName();
    name * pName = new name();
    add(pName);
    add(&varName);//error C2664: 'add' : cannot convert parameter 1 from 'name __cdecl *)(void)' to 'name *'
}


推荐答案

我认为值得告诉你一个类似的问题, / p>

I think it's worth telling you about a similar problem, that also causes trouble:

struct foo { };
struct bar { bar(foo f); };

int main() {
  // does *not* create a bar object initialized by a default constructed 
  // foo object.
  bar b(foo());
}

真正的是一个函数返回 bar 并且接受作为第一个参数的指向一个函数的指针,该函数返回一个不带参数的foo。它是相同的:

What b really is is a function that returns a bar and takes as first argument a pointer to a function that returns a foo taking no arguments. It's the same as:

bar b(foo(*)());

如果要创建一个由默认构造的foo初始化的bar对象,请在参数周围加上括号。这使它不再像一个函数声明,编译器会解释它像你想要的:

If you want to create a bar object initialized by a default constructed foo, put parentheses around the argument. That makes it doesn't look like a function declaration anymore, and the compiler will interpret it like you want:

bar b((foo()));


也是非显而易见的情况,其中编译器错误应该升高。 GCC得到这个错误,但Comeau再次得到它。考虑下面的代码片段

There are also non-obvious cases where a compiler error should be risen. GCC gets this wrong, but Comeau gets it right again. Consider the following snippet

struct foo {
  static bool const value = false;
};

int main() {
  int v(int(foo::value));
}

你可能期望这需要静态常量, code> int ,将 v 变量初始化为 0 ?不,它不会根据标准,因为初始化器可以解释为一个声明,根据纯语法分析,如下所示

You will probably expect that this takes the static constant, and casts it to int, initializing the v variable to 0? No, it won't according to the Standard, because the initializer can be interpreted as a declaration, according to pure syntax analysis, as the following shows

struct foo {
  static int value;
};

// valid, parentheses are redundant! Defines `foo::value`.
int (foo::value);

每当初始化器可以解释为一个声明,在这种情况下,整个声明将声明一个函数。因此, main 中的行声明了一个类似下面的函数,省略了多余的和无意义的括号

Whenever the initializer can be interpreted as a declaration, in such a situation whole the declaration will declare a function. So, the line in main declares a function like the following, omitting the redundant and meaningless parentheses

int v(int foo::value);

这将导致在解析函数声明时出现编译错误,因为函数参数名称可能不是合格。

And this will cause a compiler error when parsing the function declaration, because a function parameter name may not be qualified.

这篇关于这是'type variableofType()'函数还是对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆