为了账号安全,请及时绑定邮箱和手机立即绑定

为什么定义了teacher(string name ,int age)还要定义个teacher(),

这是teacher.h的代码:

#include<string>

using namespace std;
class teacher{

   public:

    teacher(string name,int age);
    void setName(string name);
    string getName();
    void setAge(int age);
    int getAge();
   private:
    string(m_strName);
    int(m_iAge);

};

这是demo.cpp的代码:

#include<iostream>
#include<string>
#include"teacher.h"

using namespace std;

int main(){
 teacher t("merry", 12);
 cout<<t.getName()<<endl;
    cout<<t.getAge()<<endl;
}

这是teacher.cpp的代码:

#include<iostream>
#include<string>
#include"teacher.h"

using namespace std;

void teacher::setName(string name)
{m_strName=name;}
string teacher::getName()
{return m_strName;}

void teacher::setAge(int age)
{m_iAge=age;}
int teacher::getAge()
{return m_iAge;}

int main(){

 teacher t;
 t.setName("kongzi");
 cout<<t.getName()<<endl;
 t.setAge(111);
 cout<<t.getAge()<<endl;

 system("pause");
 return 0;

}

这样的代码运行出来的错误是   1>d:\vs 2010\project\test8\test8\teacher.cpp(19): error C2512: “teacher”: 没有合适的默认构造函数可用
不知道怎么回事?

正在回答

2 回答

#include<iostream>

#include<string>

#include"teacher.h"

using namespace std;

void teacher::tec(string name,int age)

{

m_strName=name;

m_iAge=age;

}


string teacher::getName()

{return m_strName;}


int teacher::getAge()

{return m_iAge;}

int main(){

 teacher t;

 t.tec("wangzhengyu",24);

 cout<<t.getName()<<","<<t.getAge()<<endl;

 system("pause");

 return 0;

}

#include<string>

using namespace std;

class teacher{

   public:

    void tec(string name,int age);

    

    string getName();

   

    int getAge();

   private:

    string(m_strName);

    int(m_iAge);

};

这样也行

0 回复 有任何疑惑可以回复我~
#1

qingbpw 提问者

非常感谢!
2016-10-28 回复 有任何疑惑可以回复我~

你的 teacher(string name,int age); 这个有问题,分开 string name; int nage; 就可以了

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
C++远征之封装篇(上)
  • 参与学习       103381    人
  • 解答问题       732    个

封装--面向对象的基石,本教程力求帮助小伙伴们即学即会

进入课程

为什么定义了teacher(string name ,int age)还要定义个teacher(),

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号