【问题标题】:No viable conversion from 'Class *' to 'Class' C++从 'Class *' 到 'Class' C++ 没有可行的转换
【发布时间】:2015-03-19 02:37:48
【问题描述】:

我觉得这应该很简单,但无论出于何种原因,我都无法让它工作。

我正在尝试创建一个可以被其他函数直接传递和编辑的类的实例。

例如:

main()
{
    ClassFoo foo = new ClassFoo();
    someFunction(foo);
}

void someFunction(ClassFoo& f)
{
    f.add("bar");
}

问题是,在编译时,我最终出现了这个错误。

no viable conversion from 'ClassFoo *' to 'ClassFoo'
    ClassFoo foo = new ClassFoo();
             ^    ~~~~~~~~~~~~~~~

它还说其他候选构造函数不可行,但是在我的 ClassFoo 类中,我确实有一个如下构造函数:

ClassFoo::ClassFoo()
{}

那么我怎样才能在函数中完成对ClassFoo 变量的编辑呢?

【问题讨论】:

    标签: c++ class reference


    【解决方案1】:

    C++ 不是 Java(或者我想是 C#)。你不应该使用new 关键字,除非你know that you need to。它返回一个指向新创建的类的指针,因此会出现错误。可能,以下内容就足够了:

    Class foo;
    someFunction(foo);
    

    对于默认构造的对象,如果您不使用new,则不应包含(),因为这完全不同(请参阅the most vexing parse

    【讨论】:

    • 在现代 C++ 中您可能需要使用new 的唯一时间是为智能指针指定自定义删除器。 +1
    • 谢谢你。知道为什么在退出程序时(只在 main 中返回 0),它说pointer being freed was not allocated
    • @Alex 这意味着您在某处有一个delete 调用,它试图删除未使用new 分配的内容。请参阅:stackoverflow.com/questions/22824802/…。但就像 new 不应该出现,除非你真的知道你需要它,delete 也不应该出现。
    • Class foo(); 将是一个函数声明。 Class foo{}; 会更接近您所说的内容(尽管如果该类是一个聚合类,那么 {} 将很重要)
    【解决方案2】:

    你可能已经习惯了 C# 或类似的 sintax..

    但是,在 C++ 中,这些行之间存在很大差异:

    ClassFoo foo; //local variable at stack
    ClassFoo *foo = new ClassFoo(); //local pointer to some memory at heap which is structured like ClassFoo
    

    您可能希望第一行只是为了创建本地对象。 有很多教程描述了堆和堆栈之间的区别..所以看看它们

    【讨论】:

      猜你喜欢
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      相关资源
      最近更新 更多