The compiler cannot see the argument

I am new to C ++ and want to play around with classes.

My code

There are gerons and swords in my world. Heros carry swords. It should not be too complicated.

// Defining swords                                                                                                                                 
class Sword
{
  // The most important thing about a sword is its length.                                                                                         
  int lenght;
public:
  // only constructor and destructor                                                                                                               
  Sword(int swordlength){
    lenght = swordlength;
  };
  ~Sword(){};
};

// defining heros (as people with magic swords)                                                                                                    
class Hero
{
  Sword magic_sword;
public:
  // each hero gets a standard sword                                                                                                               
  Hero(){
    int meters = 2;
    magic_sword = Sword(meters);
  };
  ~Hero(){};
};

int main(){
  return 0;
}

What the compiler thinks about it

When I compile this code ( g++ hero.cpp), I get an error:

 In constructor 'Hero::Hero()':
20:9: error: no matching function for call to 'Sword::Sword()'
20:9: note: candidates are:
8:3: note: Sword::Sword(int)
8:3: note:   candidate expects 1 argument, 0 provided
2:7: note: constexpr Sword::Sword(const Sword&)
2:7: note:   candidate expects 1 argument, 0 provided

What i think about the problem

Compiling code with help clang++also fails, but the error message is not so explicit, so I won’t post it here.

It seems that the constructor call Sword(meters)failed because I gave 0 instead of 1 argument. But I clearly gave him an argument ( meters), so I think I missed something.

What is my mistake and what can I do about it?

+4
source share
3 answers

Hero Sword.

, , , Hero::Hero , " " Sword. , , " " Sword.

:

, ( ). ( ). (:) , , :

Hero() : magic_sword(2)
{
  // do other stuff to set up your hero
}

, magic_sword Sword::Sword(int) , , Sword::Sword() .

: ++

, Sword Hero? Hero Sword, Hero ?

, , , Hero Sword - Sword, , - nullptr , , !

+7

Sword . Hero() ( {) ,

+3

( - Java?)

. Sword , .

public:
  Hero(){
    // This point.

++ , magic_sword . Java, "null" . Sword - , Sword .

, . :

public:
  Hero() : magic_sword(2) {

  }

, Sword , Hero.

Note on your design: you most likely need magic_swordto be some kind of pointer (raw, unique or refcounting). Unlike Java, magic_swordas written, it is not a reference to an instance Sword, but is an actual instance, completely contained with the instance Hero.

+1
source

Source: https://habr.com/ru/post/1689067/


All Articles