float geht nicht
-
Warum funktioniert folgender Code mit "float" nicht?
#include <iostream> using namespace std; class trying { public: trying(); ~trying(); int func(int a) {return a;} void func(double a) {cout << a << endl;} //void func(float a) {cout << a << endl;} ??? private: }; trying::trying() { } trying::~trying() { } int main() { trying alpha; cout << alpha.func(13) << endl; alpha.func(1.1); return 0; }ERRORS bei Float:
Compiling: C:\MinGW\buch.cpp
C:\MinGW\Andi\buch.cpp: In functionint main()': C:\\MinGW\\Andi\\buch.cpp:29: error: call of overloadedfunc(double)' is ambiguous
C:\MinGW\Andi\buch.cpp:9: note: candidates are: int trying::func(int)
C:\MinGW\Andi\buch.cpp:10: note: void trying::func(float)
Process terminated with status 1 (0 minutes, 0 seconds)
3 errors, 0 warnings
-
hmm ... dummes Ding

cout << alpha.func(13) << endl;zu
std::cout << alpha.func(static_cast<int>(13)) << std::endl;und es sollte gehen.
-
das problem ist nicht int, sondern die 1.1. der compiler interpretiert das literal als double. da der auto-cast in float und int fehlerbehaftet ist, kann der compiler nicht entscheiden, welche funktion er nehmen soll. also sag dem compiler, dass es sich um einen float handelt. func(1.1f)
-
So gehts aber immer noch nicht:
#include <iostream> using namespace std; class trying { public: trying(); ~trying(); int func(int a) {return a;} void func(float a) {cout << a << endl;} private: }; trying::trying() { } trying::~trying() { } int main() { trying alpha; std::cout << alpha.func(static_cast<int>(13)) << std::endl; alpha.func(1.1); return 0; }1. Warum muss ich "std::" nehmen, wenn ich schon using namespace std nutze?
2. Ich glaub das hat gar nicht mit der "cout" Zeile zu tun.
3. Mit "double" anstatt "float" in func funktionierts ja, die Frage die sich mir stellt ist bloß warum geht es mit "double" und warum aber nicht mit "float"?Dankeschön schon mal im Voraus.
-
1. ist besser, namenskonflikte sind ne scheiss angelegenheit.
2. jo
3. double ist besser, da genauer
-
Jo dann ist klar ... dachte das du noch
void func(double a) {cout << a << endl;}drin hättest und das die angegebene Zeilennummer stimmt

#include <iostream> class trying { public: int func(int a) const { return a; } void func(float a) const { std::cout << a << std::endl;} double func(double a) const { return a; } }; int main() { trying alpha; std::cout << alpha.func(13) << std::endl; std::cout << alpha.func(12.9) << std::endl; alpha.func(1.1f); }