问题描述
- C++ 关于bool函数的一个小问题
-
/*我写的这个程序是可以运行的,但我不清楚我写的bool函数是否符合题意,因为输入不符值后输出的是三串长长的数字...麻烦大神们帮我看一下需不需要改正~可以的话,可以详细讲讲bool函数的作用和用法吗?对这个函数还是不太熟悉...*/
class CDate{ public: bool set(unsigned int yearunsigned int monthunsigned day); void print(); private: unsigned int m_nYear; unsigned int m_nMonth; unsigned int m_nDay; }; bool CDate::set(unsigned int yearunsigned int monthunsigned day) { if((month>12)||(day>31)) return false; else m_nYear=year; m_nMonth=month; m_nDay=day; return true; } void CDate::print() { cout<<m_nYear<<"" ""<<m_nMonth<<"" ""<<m_nDay; } int main(int argc char* argv[]) { CDate today; today.set(20164419); today.print(); system(""pause""); return 0; }
解决方案
1.输出一串很长的数是因为你没有初始化过,帮楼主加了一个构造函数
2.set函数里else分支应该加上括号,虽然加不加结果是一样的
3.既然set有返回值,就应该在main函数里接收该返回值,并且对于不同的返回值进行一些相应的处理
4.bool参考:http://www.cnblogs.com/JarvisChu/archive/2011/07/03/2752472.html
#include<iostream>using namespace std;class CDate{public: CDate():m_nYear(0)m_nMonth(0)m_nDay(0){} bool set(unsigned int yearunsigned int monthunsigned day); void print();private: unsigned int m_nYear; unsigned int m_nMonth; unsigned int m_nDay;};bool CDate::set(unsigned int yearunsigned int monthunsigned day){ if((month>12)||(day>31)) return false; else { m_nYear=year; m_nMonth=month; m_nDay=day; } return true;}void CDate::print(){ cout<<m_nYear<<"" ""<<m_nMonth<<"" ""<<m_nDay;}int main(int argc char* argv[]){ CDate today; bool set_res = today.set(20164419); if(!set_res) cout << ""set error"" << endl; today.print(); system(""pause""); return 0;}
解决方案二:
关于C++当中的函数作为另一个函数的参数之小问题
函数重载的一个小问题
时间: 2024-10-11 18:51:08