给一个c++构造函数例子

如题所述

第1个回答  推荐于2016-03-16
C++构造函数上唯一的语法限制是,它不能指定返回类型,甚至连void也不行(参考C++ primer14.2类的构造函数)
例子如下:
#include <iostream>

class Account {
public:
// 缺省构造函数
Account();
// 带参数的构造函数
Account(std::string name, unsigned int acct_number, double balance);

void print();
private:
std::string _name;
unsigned int _acct_number;
double _balance;
};

Account::Account()
{
this->_name = "name1";
this->_acct_number = 1;
this->_balance = 1L;
}

Account::Account(std::string name, unsigned int acct_number, double balance)
{
this->_name = name;
this->_acct_number = acct_number;
this->_balance = balance;
}

void Account::print()
{
std::cout<<"name="<<_name
<<"; acct_number="<<_acct_number
<<"; balance="<<_balance<<std::endl;
}

int main()
{
Account a1;
a1.print();

Account a2("name2", 2, 2L);
a2.print();
}

运行结果:
name=name1; acct_number=1; balance=1
name=name2; acct_number=2; balance=2本回答被网友采纳
第2个回答  2011-12-18
int funDisp(int a ,int b)
{
return (a+b);
}
/函数功能,输入两个参数求他们的和。
第3个回答  2011-12-18
你们课本上没有么

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网