简体   繁体   中英

Can't get composition right

I'm honestly embarassed I have to ask but I'm stuck on that.

#include <iostream>
using namespace std;

class Obj
{
};


class Test
{
private:
  Obj a;

public:
  Test(Obj _a)
    : a(_a) 
  {}
};


int main() {

  Obj ob();
  Test t(ob);

  return 0;

}

I get this error:

t.cpp:24: error: no matching function for call to ‘Test::Test(Obj (&)())’
t.cpp:15: note: candidates are: Test::Test(Obj)
t.cpp:10: note:                 Test::Test(const Test&)

I don't get it. The same snippet works just fine with built in types (integers and stuff).

Obj ob(); declares a ob to be a function taking no parameters and returning Obj .

If you want to default construct an Obj , use Obj ob; or Obj ob{}; .

This line

Obj ob();

does not create an object ob . It declares a function that takes nothing as input and returns a Obj .

Change it to:

Obj ob;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM