我刚写了一个简单的程序,它在一个类中有两个函数。问题是当我从main()
调用它们时,只执行第一个函数,程序终止而不调用第二个函数。
#include <stdio.h>
#include <iostream>
using namespace std;
class exp{
public:
string name;
public:
string fun1(){
cout<<"please enter value for first function ";
cin>>name;
cout<<"yourname from first function is ";
cout<<name;
return 0;
}
string fun2(){
cout<<"Please enter value for second function ";
cin>>name;
cout<<"yourname from second function is ";
cout<<name;
return 0;
}
};
int main(){
exp b1,b2;
cout << b2.fun1();
cout << b1.fun2();
}
输出
please enter value for first function preet
yourname from first function is preet
答案 0 :(得分:1)
您返回0
,而返回类型为string
。不允许从空指针构造std::string
。您可以改为使用return "";
。
答案 1 :(得分:0)
在这里,试试这个
#include <stdio.h>
#include<iostream>
using namespace std;
class exp
{
private: // changed from public to private
string name;
public:
int fun1() // changed from string to int
{
cout<<"\nplease enter value for first function ";
cin>>name;
cout<<"\nyourname from first function is ";cout<<name<<endl;
return 0;
}
int fun2() // changed from string to int
{
cout<<"\nPlease enter value for second function ";
cin>>name;
cout<<"\nyourname from second function is ";
cout<<name<<endl;
return 0;
}
};
int main()
{
exp b1,b2;
b2.fun1(); // removed cout
b1.fun2(); // removed cout
}
问题是你在函数中使用cout
,但你也在一个函数内调用它们,即cout<<b2.fun1();
。这不是一个好习惯。
还有一个问题,你的函数类型是字符串,但它们返回一个整数。
您还将name
设为public
,这只是违反了OOP的使用。所以我做了private
。
干杯......希望这能解决你的问题.. :)