C ++: default values ​​in class element

I have a problem with specifying default values ​​for my C ++ class members. My code is:

From Someclass.h:

class SomeClass
{
public:
    SomeClass();
    ~SomeClass();
    void printOut (bool);
}

... from SomeClass.cpp:

void SomeClass::printOut(bool foobar=true)
{
    if (foobar) { std::cout << foobar << std::endl; }
}

... and finally from main.cpp:

int main()
{
    SomeClass s;
    s.printOut();
    return 0;
}

However, this gives an error message (gcc):

../main.cpp: In function `int main()':
../main.cpp:8: error: no matching function for call to `SomeClass::printOut()'
../SomeClass.h:18: note: candidates are: void SomeClass::printOut(bool)
subdir.mk:21: recipe for target `main.o' failed
make: *** [main.o] Error 1

I tried to specify the default value directly in the class declaration in the header file, etc. I also tried to find both Stack Overflow and Google in general, but cannot find a solution anywhere. What am I doing wrong?

+5
source share
7 answers

You did not specify the default value for the parameter in the header as such, the compiler is looking for a signature function void printOut(void)for your statement s.printOut();, but it does not find it correctly. What you need:

class SomeClass
{
public:
    SomeClass();
    ~SomeClass();
    void printOut( bool fValue = true );  // Note change in param in definition
}

And in your cpp:

void SomeClass::printOut(bool foobar /*=true*/ )
{
    if (foobar) { std::cout << foobar << std::endl; }
}

, , .

+6

, .

class SomeClass
{
public:
    SomeClass();
    ~SomeClass();
    void printOut (bool foobar = true);   //move default here
}

void SomeClass::printOut(bool foobar)     //remove from here
{
    if (foobar) { std::cout << foobar << std::endl; }
}

, :

SomeClass s();

, . s SomeClass, s SomeClass. s.printOut(); .

, :

SomeClass s;
+4

, .

+1

:

class SomeClass
{
public:
    SomeClass();
    ~SomeClass();
    void printOut (bool value = true);
}
+1

.. note bool b = false

class SomeClass
{
public:
    SomeClass();
    ~SomeClass();
    void printOut (bool b=false);
}
+1

:

class SomeClass
{
public:
    SomeClass();
    ~SomeClass();
    void printOut (bool foobar=true);
}
+1

The default value should be specified in the declaration, not in the definition. You can specify a default value in both places, but you cannot refuse the definition. hope i confuse you. I will show the e \ corrected code so you can understand:

class SomeClass
{
public:
    SomeClass();
    ~SomeClass();
    void printOut (bool foobar = true);
}

... from SomeClass.cpp:

void SomeClass::printOut() //or you can use: void SomeClass::printOut(bool foobar=true)
{
    if (foobar) { std::cout << foobar << std::endl; }
}

... and finally from main.cpp:

int main()
{
    SomeClass s();
    s.printOut();
    return 0;
}
0
source

All Articles